Padrino - Sass, Coffee - Encoding::UndefinedConversionError, from ASCII-8BIT to UTF-8 - encoding

How to reproduce
Gemfile
gem 'haml'
gem 'sass'
gem 'coffee-script'
app/app.rb
get '/javascripts/rus_test.js' do
content_type 'text/javascript', charset: 'utf-8'
coffee :"../../public/javascripts/rus_test"
end
public/javascripts/rus_test.coffee (it's work)
alert 'Hello World!'
localhost:3000/javascripts/rus_test.js
(function() {
alert('Hello World!');
}).call(this);
public/javascripts/rus_test.coffee (doesn't work)
alert 'Привет!'
GIVES ERROR
Encoding::UndefinedConversionError at /javascripts/rus_test.js
"\xD0" from ASCII-8BIT to UTF-8
I tried to set several variants of Encoding.default in config/boot.rb.
one of variants of boot initializing
Padrino.before_load do
Encoding.default_internal = nil
# Encoding.default_external = 'ASCII-8BIT'
end
It's work for HAML with russian text, but doesn't work for SASS and COFFEE
What should I do to fix it?

Remove ridiculous Encoding.default_internal = nil and add this code somewhere to monkey patch Tilt:
# this makes tilt to treat templates as properly encoded (respect Encoding.default_external)
module Tilt
class CoffeeScriptTemplate
def prepare
#data.force_encoding Encoding.default_external
if !options.key?(:bare) and !options.key?(:no_wrap)
options[:bare] = self.class.default_bare
end
end
end
end

Related

Jump to the first file or directory that starts with a specific letter

In the VS Code Explorer, how do jump to the first file or directory that starts with a specific letter?
For example, in the node_modules directory, I want to be able to press W and jump to wcwidth in the following directory list.
.bin
abbrev
accepts
acorn
after
agent-base
align-text
amdefine
ansi-align
ansi-regex
ansi-styles
ansicolors
any-promise
anymatch
archy
argparse
arr-diff
arr-flatten
array-differ
array-find-index
array-slice
array-uniq
array-unique
arraybuffer.slice
arrify
asn1
assert-plus
async
async-done
async-each
async-each-series
async-settle
atob
aurelia-animator-css
aurelia-binding
aurelia-bootstrapper
aurelia-cli
aurelia-dependency-injection
aurelia-event-aggregator
aurelia-fetch-client
aurelia-framework
aurelia-history
aurelia-history-browser
aurelia-loader
aurelia-loader-default
aurelia-logging
aurelia-logging-console
aurelia-metadata
aurelia-pal
aurelia-pal-browser
aurelia-path
aurelia-polyfills
aurelia-route-recognizer
aurelia-router
aurelia-task-queue
aurelia-templating
aurelia-templating-binding
aurelia-templating-resources
aurelia-templating-router
aurelia-testing
aurelia-tools
aws-sign2
bach
backo2
balanced-match
base64-arraybuffer
base64id
batch
beeper
benchmark
better-assert
binary-extensions
bl
blob
bluebird
body-parser
boom
boxen
brace-expansion
braces
breeze-dag
breeze-nexttick
breeze-queue
browser-sync
browser-sync-client
browser-sync-ui
bs-recipes
builtin-modules
bytes
callsite
camelcase
camelcase-keys
capture-stack-trace
cardinal
caseless
center-align
chalk
chokidar
cli-boxes
cli-table
cli-usage
cliui
clone
clone-stats
code-point-at
colors
columnify
combined-stream
commander
component-bind
component-emitter
component-inherit
concat-map
concat-stream
configstore
connect
connect-history-api-fallback
content-type
convert-source-map
core-js
core-util-is
create-error-class
cryptiles
css
ctype
currently-unhandled
custom-event
d
dateformat
debug
decamelize
deep-extend
deep-is
default-resolution
defaults
delayed-stream
depd
destroy
detect-file
detect-indent
detect-newline
dev-ip
di
diff
dom-serialize
dot-prop
duplexer
duplexer2
duplexify
easy-extender
eazy-logger
ee-first
emitter-steward
end-of-stream
engine.io
engine.io-client
engine.io-parser
ent
error-ex
es5-ext
es6-iterator
es6-symbol
es6-weak-map
escape-html
escape-string-regexp
escodegen
esprima-fb
estraverse
esutils
etag
event-stream
eventemitter3
expand-braces
expand-brackets
expand-range
expand-tilde
express
extend
extend-shallow
extglob
fancy-log
fast-levenshtein
filename-regex
fileset
fill-range
filled-array
finalhandler
find-up
findup-sync
fined
first-chunk-stream
flagged-respawn
for-in
for-own
forever-agent
form-data
formidable
fresh
from
fs-access
fs-exists-sync
fs-extra
fs.realpath
function-bind
gaia-tsort
generate-function
generate-object-property
get-stdin
glob
glob-base
glob-parent
glob-stream
glob-watcher
global-modules
global-prefix
glogg
got
graceful-fs
graceful-readlink
growly
gulp
gulp-changed-in-place
gulp-notify
gulp-plumber
gulp-rename
gulp-sourcemaps
gulp-tslint
gulp-typescript
gulp-util
gulplog
handlebars
har-validator
has
has-ansi
has-binary
has-cors
has-flag
has-gulplog
hawk
hoek
hosted-git-info
http-errors
http-proxy
http-proxy-agent
http-signature
https-proxy-agent
iconv-lite
immutable
imurmurhash
indent-string
indexof
inflight
inherits
ini
interpret
invariant
invert-kv
is
is-absolute
is-arrayish
is-binary-path
is-buffer
is-builtin-module
is-dotfile
is-equal-shallow
is-extendable
is-extglob
is-finite
is-fullwidth-code-point
is-glob
is-my-json-valid
is-npm
is-number
is-obj
is-plain-obj
is-posix-bracket
is-primitive
is-property
is-redirect
is-relative
is-retry-allowed
is-stream
is-unc-path
is-utf8
is-valid-glob
is-windows
isarray
isbinaryfile
isexe
isobject
isstream
istanbul
jasmine-core
js-tokens
js-yaml
json-stable-stringify
json-stringify-safe
json3
jsonfile
jsonify
jsonpointer
jsrsasign
jwt-decode
karma
karma-chrome-launcher
karma-cli
karma-coverage
karma-firefox-launcher
karma-jasmine
karma-requirejs
karma-spec-reporter
karma-typescript-preprocessor
kind-of
klaw
last-run
latest-version
lazy-cache
lazy-req
lazystream
lcid
levn
liftoff
limiter
listify
load-json-file
localtunnel
lockfile
lodash
lodash.assign
lodash.assignwith
lodash.clonedeep
lodash.debounce
lodash.defaults
lodash.escape
lodash.filter
lodash.flatten
lodash.foreach
lodash.initial
lodash.isarguments
lodash.isarray
lodash.isempty
lodash.isequal
lodash.isfunction
lodash.isplainobject
lodash.isstring
lodash.keys
lodash.last
lodash.map
lodash.mapvalues
lodash.pick
lodash.reduce
lodash.restparam
lodash.sortby
lodash.template
lodash.templatesettings
lodash._arraycopy
lodash._arrayeach
lodash._baseassign
lodash._baseclone
lodash._basecopy
lodash._basefor
lodash._basetostring
lodash._basevalues
lodash._bindcallback
lodash._createassigner
lodash._getnative
lodash._isiterateecall
lodash._reescape
lodash._reevaluate
lodash._reinterpolate
lodash._root
log4js
longest
loose-envify
loud-rejection
lowercase-keys
lru-cache
make-error
make-error-cause
map-cache
map-obj
map-stream
marked
marked-terminal
matchdep
media-typer
meow
merge-stream
micromatch
mime
mime-db
mime-types
minimatch
minimist
mkdirp
ms
multipipe
mute-stdout
negotiator
next-tick
node-emoji
node-notifier
node-status-codes
node-uuid
node.extend
nopt
normalize-package-data
normalize-path
now-and-later
npm
null-check
number-is-nan
oauth-sign
object-assign
object-component
object-path
object.omit
object.pick
on-finished
once
openurl
opn
optimist
optionator
options
ordered-read-streams
os-homedir
os-locale
os-tmpdir
osenv
package-json
parse-filepath
parse-glob
parse-json
parsejson
parseqs
parseuri
parseurl
path-exists
path-is-absolute
path-root
path-root-regex
path-type
pause-stream
pify
pinkie
pinkie-promise
pkg-conf
popsicle
popsicle-proxy-agent
popsicle-retry
popsicle-status
portscanner
prelude-ls
prepend-http
preserve
pretty-hrtime
process-nextick-args
promise-finally
qs
randomatic
range-parser
raw-body
rc
read-all-stream
read-pkg
read-pkg-up
readable-stream
readdirp
rechoir
redent
redeyed
regex-cache
registry-url
repeat-element
repeat-string
repeating
replace-ext
request
require-main-filename
requirejs
requires-port
resolve
resolve-dir
resolve-url
resp-modifier
right-align
rimraf
rx
semver
semver-diff
semver-greatest-satisfied-range
semver-regex
send
serve-index
serve-static
server-destroy
set-blocking
set-immediate-shim
setprototypeof
shellwords
signal-exit
slide
sntp
socket.io
socket.io-adapter
socket.io-client
socket.io-parser
sort-keys
source-map
source-map-resolve
source-map-url
sparkles
spdx-correct
spdx-exceptions
spdx-expression-parse
spdx-license-ids
split
sprintf-js
stack-trace
statuses
stream-combiner
stream-exhaust
stream-shift
stream-throttle
string-template
string-width
stringstream
string_decoder
strip-ansi
strip-bom
strip-bom-stream
strip-indent
strip-json-comments
supports-color
symbol
text
tfunk
thenify
throat
through
through2
through2-filter
throwback
tildify
time-stamp
timed-out
to-absolute-glob
to-array
touch
tough-cookie
trim-newlines
tslint
tunnel-agent
type-check
type-is
typedarray
typescript
typings
typings-core
ua-parser-js
uglify-js
uglify-to-browserify
ultron
unc-path-regex
underscore
underscore.string
undertaker
undertaker-registry
unique-stream
unpipe
unzip-response
update-notifier
urix
url-parse-lax
user-home
useragent
utf8
util-deprecate
utils-merge
uuid
v8flags
vali-date
validate-npm-package-license
vinyl
vinyl-fs
void-elements
wcwidth
weinre
whatwg-fetch
which
widest-line
window-size
wordwrap
wrap-ansi
wrappy
wreck
write-file-atomic
ws
xdg-basedir
xmlhttprequest-ssl
xtend
y18n
yargs
yargs-parser
yeast
zip-object
This already works in the Windows File Explorer. It's called "When typing into list view, Select the typed item in the view." Does a similar feature exist in the Visual Studio Code Explorer?

Mason2 wrong utf8 encoding with the "go" method

Bit long question, because AFAIK Poet/Mason2 isn't the very often used framework - so I'm trying to be detailed.
Two years ago I asked a question how to make Mason2 utf8 clean. As far as i know, here isn't much new in Mason/Poet in this field - and unfortunately today I meet another problem. Simple test case:
$ poet new my #create new poet application
$ cd my
Override some methods, allowing to use utf8 in the components:
add to ./lib/My/Mason/Compilation.pm
override 'output_class_header' => sub {
return join("\n",
super(), qq(
use utf8;
use Encode qw(encode decode);
)
);
};
The above adds to each compiled Mason component the use utf8....
Also need encode the output from Mason (Plack need bytes), so in: ./lib/My/Mason/Request.pm
override 'run' => sub {
my($self, $path, $args) = #_;
my $result = super();
$result->output( Encode::encode('UTF-8', $result->output()) );
return $result;
};
Now, can create a component such page.mc for example with a content:
% sub { uc($_[0]) } {{
a quick brown fox jumps over the lazy dog.
διαφυλάξτε γενικά τη ζωή σας από βαθειά ψυχικά τραύματα.
árvíztűrő tükörfúrógép.
dość gróźb fuzją, klnę, pych i małżeństw!
эх, чужак, общий съём цен шляп (юфть) – вдрызг!
kŕdeľ šťastných ďatľov učí pri ústí váhu mĺkveho koňa obhrýzať kôru a žrať čerstvé mäso.
zwölf boxkämpfer jagen viktor quer über den großen sylter deich.
% }}
After running a poet app bin/run.pl you can go to: http://0:5000/page and will get a correct content.
A QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ΔΙΑΦΥΛΆΞΤΕ ΓΕΝΙΚΆ ΤΗ ΖΩΉ
ΣΑΣ ΑΠΌ ΒΑΘΕΙΆ ΨΥΧΙΚΆ ΤΡΑΎΜΑΤΑ. ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP. DOŚĆ GRÓŹB
FUZJĄ, KLNĘ, PYCH I MAŁŻEŃSTW! ЭХ, ЧУЖАК, ОБЩИЙ СЪЁМ ЦЕН ШЛЯП (ЮФТЬ) –
ВДРЫЗГ! KŔDEĽ ŠŤASTNÝCH ĎATĽOV UČÍ PRI ÚSTÍ VÁHU MĹKVEHO KOŇA OBHRÝZAŤ
KÔRU A ŽRAŤ ČERSTVÉ MÄSO. ZWÖLF BOXKÄMPFER JAGEN VIKTOR QUER ÜBER DEN
GROSSEN SYLTER DEICH.
But when create another component, say go.mc with a content
% $m->go('/page');
the internal redirect (the go method) somewhat mess up the content and will produce:
A QUICK BROWN FOX JUMPS OVER THE LAZY DOG. ÎÎÎΦΥÎÎÎΤÎ
ÎÎÎÎÎΠΤΠÎΩΠΣÎΣ ÎÎ Î ÎÎÎÎÎΠΨΥΧÎÎÎ
ΤΡÎÎÎÎΤÎ. ÃRVÃZTÅ°RÅ TÃKÃRFÃRÃGÃP. DOÅÄ GRÃŹB
FUZJÄ, KLNÄ, PYCH I MAÅÅ»EÅSTW! ЭХ, ЧУÐÐÐ, ÐÐЩÐÐ
СЪÐРЦÐРШÐЯР(ЮФТЬ) â ÐÐРЫÐÐ! KÅDEĽ Å
ŤASTNÃCH ÄATĽOV UÄà PRI ÃSTà VÃHU MĹKVEHO KOÅA OBHRÃZAŤ
KÃRU A ŽRAŤ ÄERSTVà MÃSO. ZWÃLF BOXKÃMPFER JAGEN VIKTOR QUER
ÃBER DEN GROSSEN SYLTER DEICH.
Strange, the $m->visit() works correctly. So, somewhere in Poet/Mason is need do something to get correct output for the go method.
Could anyone help?
I've been working on a plugin for Mason to deal with encoding. $result->output is the wrong place to encode output, because visit will run a subrequest, encoding its own content at the end, before returning to the original component, which then re-encodes everything when it completes. So the content in the visit gets encoded twice. I'm surprised you are having a problem with go, because that discards all previous content and starts again, which should be OK.
Have a look at https://github.com/davebaird/mason-plugin-withencoding

not loading images in rack application

I created a simple rack application to display the specified directory contents. But the problem is if directory have any img file I want it to display in a small thumbnail.
"
require 'rubygems'
require 'rack'
require 'rack/server'
class EnvInspector
def self.call(env)
request = Rack::Request.new env
#name=request.params["path"]
#name.prepend("/home/")
#result="";
if File::directory?((#name.to_s))
Dir.foreach(#name) do |item|
item=item.sub(/([^\s]+(\.(?i)(jpg|png|gif|bmp))$)/,"<img src=\"#{#name}\/\\0\" width=100px height=100px/>")
#result =#result + "<li>#{item}</li>"
end
#result.prepend("<ul>");
#result+="</ul>";
[200, {"Content-Type"=>"text/html"},["##result"]]
else
[200, {"Content-Type"=>"text/html"},["No file in this directory"]]
end
end
end
Rack::Server.start :app => EnvInspector "
It is not showing the image in the browser. Even the browser getting the correct img path.
Resolved this issue with giving relative path to image url
require 'rubygems'
require 'rack'
require 'base64'
require 'rack/server'
require 'nokogiri'
class EnvInspector
def self.call(env)
request = Rack::Request.new env
#name=request.params["path"]
#name.prepend("/home/")
#result="";
if File::directory?((#name.to_s))
Dir.foreach(#name) do |item|
fname = item
if fname.match(/([^\s]+(\.(?i)(jpg|png|gif|bmp))$)/)
file = File.open("#{#name}/#{item}")
data = file.read
img_encoded = Base64.encode64(data)
items = "<img src='data:image/*;base64, #{img_encoded}' width= 100px height=100px/>"
#result =#result + "<li class=\"list-group-item\">#{items}</li>"
else
#result=#result + "<li>#{item}</li>"
end
end
#result.prepend("<ul>");
#result+="</ul>";
[200, {"Content-Type"=>"text/html"},["##result"]]
else
[200, {"Content-Type"=>"text/html"},["No file in this directory"]]
end
end
end
Rack::Server.start :app => EnvInspector

How can I do continuous build/unit testing in Coffeescript?

I'm writing a (ever larger) set of unit tests using Coffeescript and node.js. I build the files using the coffee "watch" option (-w)
coffee -w -b -c -o web/ src/
My problem is that running the unit tests takes 20 secs (I'm assuming for the compile to .js).
If possible, I'd like automatically run the unit tests on a (compiled .js) file change, which would eliminate the long wait for the results.
My current Cakefile:
fs = require 'fs'
{print} = require 'sys'
{spawn, exec} = require 'child_process'
build = (watch, callback) ->
if typeof watch is 'function'
callback = watch
watch = false
options = ['-c', '-b', '-o', 'web', 'src']
options.unshift '-w' if watch
coffee = spawn 'coffee', options
coffee.stdout.on 'data', (data) -> print data.toString()
coffee.stderr.on 'data', (data) -> print data.toString()
coffee.on 'exit', (status) -> callback?() if status is 0
task 'test', 'Run the test suite', ->
build ->
require.paths.unshift __dirname + "/lib"
{reporters} = require 'nodeunit'
process.chdir __dirname
reporters.default.run ['test']
Take a look at the Cakefile for my connect-assets project: https://github.com/adunkman/connect-assets/blob/master/Cakefile
It's a bit more complex than sstephenson's (which I assume your example is derived from), but it shows how you can watch a directory of files for changes and respond to those changes by re-running tests.

Setting env when using rspec to test omniauth callbacks

I'm having a strange problem when trying to set a callback for Facebook Authentication via Omniauth. In my controller (simplified to just the code necessary to show the error) I have:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
raise env.inspect
# auth_hash = env["omniauth.auth"]
end
end
this works in production mode, showing me the hash. However in test mode env is set to nil.
I have the following set in my spec_helper.rb file
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:facebook, {"credentials" => {
"token" => "foo-token"
}
})
and my spec looks like this:
require 'spec_helper'
describe Users::OmniauthCallbacksController do
describe "Facebook" do
before(:each) do
request.env["devise.mapping"] = Devise.mappings[:user]
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
end
it "should be a redirect" do
get :facebook
response.should redirect_to(root_path)
end
end
end
Can anyone enlighten me on what I need to do to have env not be nil when running my tests?
I use the following in my spec_helper.rb :
RACK_ENV = ENV['ENVIRONMENT'] ||= 'test'
I don't use Rails or Devise though so YMMV. I've also seen various threads saying that someone had to do this before their requires to get it to work.