Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if class method is called externally or internally

Tags:

ruby

class MyParent
  def self.foo
    if this_method_was_called_internally?
      puts "yay" 
    else
      puts "boo"
    end
  end
end

class MyLibrary < MyParent
  foo # yay
end

MyLibrary.foo # boo

Is this possible?

like image 444
RyanScottLewis Avatar asked Oct 12 '22 04:10

RyanScottLewis


2 Answers

The simple answer is no. You can however play with caller, it gives you access to the call stack, much like an exception backtrace:

def this_method_was_called_internally?
  caller[1].include?(...)
end

(caller[1] would be the previous call, i.e. the method calling this_method...)

It's very hackish, and the information you get from caller may not be enough.

Please don't use this other than to experiment.

like image 193
Theo Avatar answered Oct 15 '22 09:10

Theo


If you can afford a little modification of your code:

class MyParent
  def self.foo(scope)
    if scope == self
      puts "yay" 
    else
      puts "boo"
    end
  end
end

class MyLibrary < MyParent
  foo(self) # yay
end

MyLibrary.foo(self) # boo
like image 41
Vasiliy Ermolovich Avatar answered Oct 15 '22 11:10

Vasiliy Ermolovich