tags:

views:

106

answers:

2

Can someone please tell me what

send("{Model.find...}")

is and does?

+5  A: 

send is a ruby (without rails) method allowing to invoke another method by name.

From documentation

   class Klass
     def hello(*args)
       "Hello " + args.join(' ')
     end
   end
   k = Klass.new
   k.send :hello, "gentle", "readers"   #=> "Hello gentle readers"

http://corelib.rubyonrails.org/classes/Object.html#M001077

Nikita Rybak
+2  A: 

send sends a message to an object instance and its ancestors in class hierarchy until some method reacts (because its name matches the first argument).

Practically speaking, those lines are equivalent:

1.send '+', 2
1.+(2)
1 + 2

Note that send bypasses visibility checks, so that you can call private methods, too (useful for unit testing).


If there is really no variable before send, that means that the global Object is used:

send :to_s    # "main"
send :class   # Object
giraff
Oh I see, so one might use send if one wanted to store something like 1.month on the database instead of statically saying the number of days.
Christian Bankester
True, you could use it to call method with names that are computed, not static. (You shouldn't allow unrestricted user input, though, to avoid calling private methods... You could, however, give them a unique prefix: send 'user_method_'+methodname, *args)
giraff
Okay, so I need something like this:time_span = "1.month";date = some DateTime;date = date + send("#{time_span}");but that doesn't seem to work...
Christian Bankester