Sonia Hamilton
Sonia Hamilton

Reputation: 4419

Getting the name of a method used as a block in Ruby

If a method is called in a block, how do I get it's name? For example, I have this simple logger (adapted from Ross Olsen's book Eloquent Ruby):

def self.with_logging(text, &block)
  begin
    puts ">> START:  #{text}"
    yield if block_given?
    puts "<< END:    #{text}"
  rescue
    puts "-- FAILED: #{text}"
    raise
  end
end

and I use it to log calls to method foo like this:

with_logging('foo') { foo }

The method name foo is repeated in both the text parameter and the block for with_logging. I'd like to remove this duplication, making the text parameter default to the name of the method used in the block, but how would I find the method's name?

Upvotes: 0

Views: 68

Answers (1)

sawa
sawa

Reputation: 168131

It is impossible to do that unless with meta-programming that looks into the parsed result of the code.

But you can do the other way around. Given the name of the method and absence of a block, you can make it call that method in the block by default.

def self.with_logging(text)
  begin
    puts ">> START:  #{text}"
    block_given? yield : send(text)
    puts "<< END:    #{text}"
  rescue
    puts "-- FAILED: #{text}"
    raise
  end
end

Upvotes: 2

Related Questions