Ruby: Dynamic method call using send method
Hi friends,
As everybody says rails is a dynamic language. They says this because of its functionalities that makes it dynamic. One of the feature of rails is it's send method. It is an instance method of Object class, in this you can pass the message to which you want to call. Thus if you have method name in string format you can pass it here so the first argument of the send becomes the method name and the rest becomes the argument to that method itself.
Thus by using this method depending on different conditions you can call different methods dynamically. Lets take an example that I shared in my previous blog Ruby: Metaprogramming: Method that makes methods, that suppose we have 3 different methods that just tells the status of 3 different types of users, then we can call them dynamically
class User
["doctor", "patient", "guest"].each do |action|
define_method("validate_#{action}") do |arg|
"#{action.gsub('_', ' ')} is #{arg}"
end
end
end
user = User.new
## Normal approach
puts user.validate_doctor("active")
puts user.validate_patient("inactive")
puts user.validate_guest("active")
#=> Output
doctor is active
patient is inactive
guest is active
## Dynamically calling using send
puts user.send("validate_doctor", "active")
puts user.send("validate_patient", "inactive")
puts user.send("validate_guest","active")
#=> Output
doctor is active
patient is inactive
guest is active
So we saw here that it makes work more dynamic by using strings into method call, thus the method name or a part of it can be passed into another method and depending on that parameter the passed method can be called. Lets do a little modification in the above example.
class User
["doctor", "patient", "guest"].each do |action|
define_method("validate_#{action}") do |arg|
"#{action.gsub('_', ' ')} is #{arg}"
end
end
def get_status user_type, status
send("validate_#{user_type}", status)
end
end
user = User.new
puts user.get_status("doctor", "active")
puts user.get_status("patient", "inactive")
puts user.get_status("guest","active")
Thus here we made one method get_status and called the method dynamically. Hope you liked reading this blog. For more like this Click here.
0 Comment(s)