Error: "undefined local variable or method '__method__'"

40 views
Skip to first unread message

Daniel Huffman

unread,
Nov 15, 2016, 11:46:16 AM11/15/16
to Crystal
How do you programmatically get the current method name?

For example, in Ruby, you can do something like:

def some_method(params)
  logger.warn("#{self.class.name}##{__method__} -> params: #{params}")
  # ..
end

.. or ..

def some_method
  # ..
  condition = ...
  logger.warn("#{self.class.name}##{__method__} -> condition met!") if condition
  # ..
end

Daniel Huffman

unread,
Nov 16, 2016, 10:27:27 AM11/16/16
to Crystal
See also: https://github.com/crystal-lang/crystal/issues/3552 for a "we could add" potential solution:

def foo 
  # a.k.a. __method__
  {{@def.name.stringify}} # => "foo"
end


Kingsley Lewis

unread,
Nov 16, 2016, 12:38:12 PM11/16/16
to Crystal
If you want to do something that's kind of a kludge you can use caller, to get the current call stack.


p caller[4] if condition
Reply all
Reply to author
Forward
0 new messages