Ruby on Rails console, beginner error - ruby-on-rails

In rails console when I want to add a column to my table with below command
2.1.1 :001 >post = Post.new( :title => "first post", :job => "first job”)
it gives me
2.1.1 :002">
2.1.1 :003">
2.1.1 :004">
and doing nothing! I don't know what is problem here?

You didn't close quotes.
"first job”
Note that ” are not the same as " Console is waiting for you to close all the brackets and quotes before it executes the command.

if you copied and pasted the code the problem is with the last double-quotes
'”'.ord #=> 8221
'"'.ord #=> 34
'”' == '"' #=> false

Related

How do I write a function in rails console?

I am trying to write a function in the rails console, and in the example, this is how the function should look in terminal.
>> def string_message(str = '')
>> return "It's an empty string!" if str.empty?
>> return "The string is nonempty."
>> end
How do they create a new line while still making the console realize it is all of the lines create a function. Would it be accurate to write it as:
>> def string_message(str = '') \n\t return "It's an empty string!" if str.empty? \n\t blah blah \n\t
?
IRB, the ruby console in which rails console relies supports this out of the box.
Just type your function declaration, press the enter key, then input the body line by line, and finally type end.
You'll see text like this:
2.4.1 :001 > def say_hi(person)
2.4.1 :002?> puts "Hi #{person}"
2.4.1 :003?> end
=> :say_hi
2.4.1 :004 > say_hi("Nina")
Hi Nina
=> nil
2.4.1 :005 >
Notice how the ? indicates that IRB is waiting for more input before evaluating the expression.

String start with # return with backslash in rails console in some case

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

Ruby gsub not replacing newline character

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).

Ruby: How to remove trailing backslashes from a string?

I have a string like
"car\"
which I will be storing in postgres db. I want to remove the backslash from the string before saving. Is there a way I can do that in ruby or in postgres? When I try to remove it in ruby, it considers the quote after the backslash as an escape character.
See following code:
1.9.3p125 :022 > s = "cat\\"
=> "cat\\"
1.9.3p125 :023 > puts s
cat\
=> nil
1.9.3p125 :024 > s.chomp("\\")
=> "cat"
1.9.3p125 :025 >
People don't do this much, but Ruby's String class supports:
irb(main):002:0> str = 'car\\'
=> "car\\"
irb(main):003:0> str[/\\$/] = ''
=> ""
irb(main):004:0> str
=> "car"
It's a conditional search for a trailing '\', and replacement with an empty string.
To remove a trailing backslash:
"car\\".gsub!(/\\$/, "")
Note that the backslash has to be escaped itself with a backslash.
puts '"car\"'.gsub(/\\(")?$/, '\1')
that will do it,
but, is the trailing slash always at the en followed by a quote?
See what says the
str.dump
operation, and then try to operate on that.

Rails / Ruby not following Rublar on regular expression

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.

Resources