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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With