Problem:
being a german dev I often have Umlaute in my strings, comments, etc. When pasting those into the rails console though it renders the prompt unresponding. It can only be resolved by quitting and restarting the rails-console
Request:
Any way I can configure or fix the console so it accepts special chars as input
Example:
# paste in console to render it useless
def is_a_test
puts "it's a string with ä ö and ü"
end
leads to this on console:
irb(main):004:0> # paste in console to render it useless
=> nil
irb(main):005:0> def is_a_test
irb(main):006:1> puts "it's a string with
irb(main):007:1"
irb(main):008:1" ^C
irb(main):008:0>
Thanks in advance
Related
In console of rails 4.2.7, I have the following test:
[45] pry(main)> '#$'
=> "\#$"
[46] pry(main)> '##'
=> "\##"
[47] pry(main)> '#!'
=> "#!"
[48] pry(main)> '#ab'
=> "#ab"
It seems rails will only put a "\" before the string when there is an # or $ after #.
The problem leads me to this test is that I have a erb file that render a data attribute with an array of json:
data-xx="<%= [{xx: '#$', yy: 'yy'}.to_json, {zz: 'zzz'}.to_json] %>"
Then in chrome console, it will give the unexpected result as
$("#entry_show_modal_template").data('xx')
"["{\"xx\":\"\#$\",\"yy\":\"yy\"}", "{\"zz\":\"zzz\"}"]"
And when I change xx value from #! or some other string, the result will be ok as an array
$("#entry_show_modal_template").data('xx')
["{"xx":"#!","yy":"yy"}", "{"zz":"zzz"}"]
Does someone know if it is true and why it has such difference?
And it there any way to tackle this problem?
This is not true.
In '#{...}' hash will also be escaped. This is done to prevent recursive/implicit string interpolation.
Look:
$a = 'hello'
"#$a"
#⇒ "hello"
The problem is already solved by ruby for you. Just use the produced string as is and don’t be fooled by the way it is printed out in console.
"\#$".length
#⇒ 2
"\#$" == '#$'
#⇒ true
"\#$"[0]
#⇒ "#"
#mudasobwa's explaination is correct
According to your situation you should try in this way
===> In rails console
json_values = [{xx: '#$', yy: 'yy'}, {zz: 'zzz'}].to_json
===> In chrome console
result = JSON.parse(json_values)
you will get expected array, its just ruby technique to handle string interpolation thing
I have this code
str = #universal_claim_form.errors.full_messages.join
str.gsub('Patient Contact Information: Value', 'Patient phone number') if str =~ /Patient Contact Information/
debugger
str.gsub("\\n", "<br/>")
debugger
flash.now[:error] = "Form has errors and was unable to be submitted.<br/> " << str
the first gsub replaces an unwanted message and the second gsub it meant to replace all the newline characters with html line breaks
at the first debugger line str = "PMP Validation failed. This happens when something you entered does not pass PMP specific validations.\\nPatient phone number: Value must be a 10 digit number"
and at the second debugger the line hasn't changed
what's even more weird is that I did this in irb at the command line and it worked
2.1.1 :001 > s = 'test'
=> "test"
2.1.1 :002 > s
=> "test"
2.1.1 :003 > s += '\ntest'
=> "test\\ntest"
2.1.1 :004 > s.gsub('\\n', '<br/>')
=> "test<br/>test"
2.1.1 :005 >
You can call gsub! to mutate the string you are calling it on (instead of returning a new string).
The reason gsub "works" in irb is because it is outputting the result - irb does not do any assignment or mutation (beyond what one enters), e.g.
irb(main):001:0> foo = 4
=> 4
irb(main):002:0> foo + 6
=> 10
foo is getting assigned 4 so it outputs the result of that assignment, likewise with foo + 6 it outputs the result but the value of foo is unchanged.
When you call gsub it returns a new string with the substitution(s), this is why you feel it "works" in irb (this is no different then it printing "4" above).
I have the following expression that I have tested in Rubular and that successfully matches against a snippet of HTML:
Official Website<\/h3>\s*<p><a href="([^"]*)"
However, when I run the expression in Ruby, using the following code, it returns no matches. I've reduced it down to "Official\s*Website" and it matches that, but nothing further.
Are there any additional options I need to set, or anything else that I need to do to configure Ruby/Rails to start tracking Rubular?
matches = sidebar.match(/Official\s*Website<\/h3>\s*<p><a href="([^"]*)"/)
if matches.nil?
puts "no matches"
else
puts "matches"
end
This is the relevant part of the snippet I'm matching against:
<h3>Official Website</h3><p>website.com</p>
your regular expression is correct. rubular should be working the same way your code does.
i tested it against ruby 1.8.7 and 1.9.3
irb(main):006:0> sidebar = ' <h3>Official Website</h3><p>website.com</p>'
=> " <h3>Official Website</h3><p>website.com</p>"
irb(main):007:0> sidebar.match(/Official\s*Website<\/h3>\s*<p><a href="([^"]*)"/)
=> #<MatchData "Official Website</h3><p><a href=\"http://website.com\"" 1:"http://website.com">
-
1.9.3p0 :005 > sidebar = ' <h3>Official Website</h3><p>website.com</p>'
=> " <h3>Official Website</h3><p>website.com</p>"
1.9.3p0 :006 > sidebar.match(/Official\s*Website<\/h3>\s*<p><a href="([^"]*)"/)
=> #<MatchData "Official Website</h3><p><a href=\"http://website.com\"" 1:"http://website.com">
if you want to quickly check why stuff is not working, you should try it in IRB or in your rails console. most of the times it's typo or bad encoding.
I am uploading an image with a file name containing an umlaut via dragonfly in a Rails 3 app on Heroku. Then I'm trying to display the image using
image_tag #model.image.url, …
In development everything works just fine, but in production I'm getting:
incompatible character encodings: UTF-8 and ASCII-8BIT
.bundle/gems/ruby/1.9.1/gems/actionpack-3.0.7/lib/action_view/helpers/tag_helper.rb:129:in `*'
After reading a bit I've added
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
in environment.rb but the problem remains.
What is the proper way to go about this? Do I have to fix the file name when uploading? I was under the impression this should work just fine in Rails 3?
Well, you could try something like url.force_encoding('utf8')
You could also simply sanitize the url in the model before saving it to the database - that's what I did. And, yes, I sometimes stumble over this in the weirdest places, too.
This is what my model looked like:
# encoding: UTF-8
class Page < ActiveRecord::Base
before_save :sanitize_title
private
def sanitize_title
self.title = self.title.force_encoding('UTF-8').downcase.gsub(/[ \-äöüß]/, ' ' => '_', '-' => '_', 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss').gsub(/[^a-z_]/,'')
end
end
This will replace the German umlaute with their ASCII counterparts, convert spaces to underscores and drop everything else.
The first line # encoding: UTF-8 is important or ruby will complain of non-ASCII characters in the model.rb file...
In addition to #Rhywden's answer, here my solution specific for Dragonfly:
image_accessor :image do :after_assign
after_assign{|i| i.name = sanitize_filename(image.name) }
end
def sanitize_filename(filename)
filename.strip.tap do |name|
name.sub! /\A.*(\\|\/)/, ''
name.gsub! /[^\w\.\-]/, '_'
end
end
Details here http://markevans.github.com/dragonfly/file.Models.html and here http://guides.rubyonrails.org/security.html#file-uploads .
I am facing "Illegal quoting" error when parse the content from SQL dump and the dump file is in the format of TXT with tab (\t) separator.
require 'rubygems'
require 'faster_csv'
begin
FasterCSV.foreach(excel_file, :quote_char => '"',:col_sep =>'\t', :row_sep =>:auto, :headers => :first_row) do |row|
col= row.to_s.split(/\t/)
if col[3]!="" or !col[3].empty?
color_value=col[3].to_s.capitalize
#Inser Color
color=Color.find_or_create_by_name(:name=>color_value)
elsif col[3].empty?
color_id= nil
end
end
rescue Exception => e
puts e
end
The program executed and run successfully but there is an invalid data present like
below (#font-face ...) mean execution terminated with error of "Illegal quoting on line 3.
ID Name code comments
1 white 234 good
2 Black 222
3 red 343 #font-face { font-family: "Verdana"; .....}
Can any one suggest me how to skip when invalid data occurs in column ?
Thanks in advance.
I'm not sure if this will solve the error you are seeing, but you need to use double quotes around escaped characters, e.g.:
:col_sep => "\t"
FasterCSV isn't very kind to badly formatted data.
I don't know that there is a solution for this.
However - if your example file doesn't actually contain any quoting using "
then perhaps just use a different quot_char (eg ')
You can use the ASCII code for the NULL character -- \0x00 -- as such:
FasterCSV.foreach(excel_file, :quote_char => '\0x00',:col_sep =>'\t', :row_sep =>:auto, :headers => :first_row) do |row|
...
end
You can find a chart of some ASCII chars here: http://www.bluesock.org/~willg/dev/ascii.html