How do I write a function in rails console? - ruby-on-rails

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.

Related

rails saving recognized link from text to database with rinku

I have a rails app with chat. In the chat for the messages I use rinku gem to recognize links which works well. On the top of this I would like to save the links as message.link without the rest of the text around it from the message.body.
So for example in the code below the user sent the message.body "hi there www.stackoverflow.com" and I would like to save only the "www.stackoverflow.com" as message.link. How can I do that?
view
<p><%= find_links(message.body) %></p>
controller
def find_links(message_body)
Rinku.auto_link(message_body, mode=:all, 'target="_blank"', skip_tags=nil).html_safe
end
it will appear in the DOM as:
<p>hey there http://stackoverflow.com/</p>
and will appear in the db as message.body:
"hey there http://stackoverflow.com/"
UPDATE:
messages controller
require "uri"
def create
.....
if message.save
link = URI.extract(message.body)
update_attribute(message.link = link)
end
You need regular expression to identify URLs from text. Try following regular expression:
/(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/
Working demo: http://rubular.com/r/bHQdFHZYFH
2.1.2 :001 > str = "hey hi hello www.google.com https://stackoverflow.com http://tech-brains.blogspot.in"
2.1.2 :002 > regexp = /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/
2.1.2 :003 > str.scan(regexp)
=> [["www.google.com"], ["https://stackoverflow.com"], ["http://tech-brains.blogspot.in"]]
You can use Ruby code:
2.0.0-p247 :001 > require "uri"
=> true
2.0.0-p247 :002 > URI.extract("hey there http://stackoverflow.com/")
=> ["http://stackoverflow.com/"]
Hope it helps!

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

In Ruby 1.9.3, check if the user input is a directory

#!/usr/bin/ruby
puts "Please enter the path-name of the directory:"
p = STDIN.gets
isdir = File.directory?(p)
puts "#{isdir} #{p}"
it always return me a false! even though I know the user input is a directory. I think (p) is not working as a parameter. So i think its saying that p is not a directory not the user input for example "/usr/bin/". any help?
Using p = STDIN.gets '\n' was getting appended. Instead you can use gets.chomp. Also you need to use File.expand_path. Check the example below.
# My irb
1.9.3-p545 :002 > p = gets.chomp
~/.ssh
=> "~/.ssh"
1.9.3-p545 :003 > File.directory?(p)
=> false
1.9.3-p545 :004 > File.exists? File.expand_path(p)
=> true
The p value is not strictly equal to what you expect it to be. It contains \n at the end:
# in my irb:
1.9.3p392 :010 > p = STDIN.gets
/home/
=> "/home/\n"
1.9.3p392 :011 > isdir = File.directory?(p)
=> false
1.9.3p392 :012 > isdir = File.directory?(p.strip)
=> true
The strip method:
Strips entire range of Unicode whitespace from the right and left of the string.
Source: http://apidock.com/rails/ActiveSupport/Multibyte/Chars/strip

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.

opening Array in ruby on rails console v. irb

I wish to make my code a little more readable by calling #rando on any array and retrieve a random element (rando because a rand() method already exists and I don't want there to be any confusion).
So I opened up the class and wrote a method:
class Array
def rando
self[ rand(length) ]
end
end
This seems far too straightforward.
When I open up irb, and type arr = %w(hi bye) and then arr.rando I get either hi or bye back. That's expected. However, in my rails console, when I do the same thing, I get ArgumentError: wrong number of arguments (1 for 0)
I've been tracing Array up the rails chain and can't figure it out. Any idea?
FWIW, I'm using rails 2.3.11 and ruby 1.8.7
Works fine in my case :
Loading development environment (Rails 3.0.3)
ruby-1.9.2-p180 :001 > class Array
ruby-1.9.2-p180 :002?> def rando
ruby-1.9.2-p180 :003?> self[ rand(length) ]
ruby-1.9.2-p180 :004?> end
ruby-1.9.2-p180 :005?> end
=> nil
ruby-1.9.2-p180 :006 > arr = %w(hi bye)
=> ["hi", "bye"]
ruby-1.9.2-p180 :007 > arr.rando
=> "bye"

Resources