Rails 100% newb issue - send() method

一笑奈何 提交于 2019-12-02 17:05:48

The Ruby implementation for the send method, which is used to send a method message to an object, works like this:

class Car

  def start
    puts "vroom"
  end

  private

  def engine_temp
    puts "Just Right"
  end

end

@car = Car.new
@car.start # output: vroom
@car.send(:start) # output: vroom

That's the basics, an additional piece of important information is that send will allow you you send in messages to PRIVATE methods, not just public ones.

@car.engine_temp  # This doesn't work, it will raise an exception
@car.send(:engine_temp)  # output: Just Right

As for what your specific send call will do, more than likely there is a def method_missing in the Performer class that is setup to catch that and perform some action.

Hope this helps, good luck!

send is used to pass a method (and arguments) to an object. It's really handy when you don't know in advance the name of the method, because it's represented as a mere string or symbol.

Ex: Performer.find(params[:performer_id]) is the same as Performer.send(:find, params[:performer_id])

Beware here because relying on params when using send could be dangerous: what if users pass destroy or delete? It would actually delete your object.

The send method is the equivalent of calling the given method on the object. So if the selected_track variable has a value of 1234, then @performer.send(selected_track) is the same as @performer.1234. Or, if selected_track is "a_whiter_shade_of_pale" then it's like calling @performer.a_whiter_shade_of_pale.

Presumably, then, the Performer class overrides method_missing such that you can call it with any track (name or ID, it isn't clear from the above), and it will interpret that as a search for that track within that performer's tracks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!