Canna
Canna

Reputation: 3794

How to send symbol as method in Ruby?

Example,

I'll use a Rails ActiveRecord Callback

before_validation :foobar

def foobar
 logger.debug 'before validate'
end

if i send the method as symbol this callback executes well.

My question is, this is not a normal case!

Ruby cannot send method as param, except block, Proc, lambda, isn't it?

This is reasonable for me.

before_validation -> {logger.debug 'before validate'}

But how could this work?

before_validation :foobar

So i made my own methods, same as this.

  do_something(:my_callback)

  def do_something(my_callback)
    my_callback
    logger.debug "somesomesome"
  end

  def my_callback
    logger.debug "calcalcalcal"
  end

and the result is?

ofcourse, this is not working!

my_callback param is just a plain symbol :(

Upvotes: 1

Views: 554

Answers (2)

Milind
Milind

Reputation: 5112

Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. There are three ways to call method in ruby:

1)Dot operator

object = Object.new
puts object.object_id
 #=> 282660

2)Using send (API )

puts object.send(:object_id)
 #=> 282660

3)Using method.call

puts object.method(:object_id).call
 #=> 289744

So here the symbol :object_id can also be a reference to your method such as :my_callback

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

You should use Object#send:

def do_something(my_callback)
  send my_callback
end

or if you want it to be more generic (so you can pass arguments/block to it:

def do_something(my_callback, *args, &block)
  send my_callback, *args, &block
end

Upvotes: 4

Related Questions