I'd like to add something about their keyword-like behavior, because the answers have been more about where than how; the answer lies in the complex metaprogramming capabilities of Ruby.
It is possible to use them as keywords making use of the method_added
hook; an hook in Ruby is a function that is called when a specific event (i.e. the hook's name) occurs.
What's important is that the method_added
hook receives as his argument the name of the method that has been defined: this way, it's possible to modify it's behavior.
For example, you could use this hook to define a behavior similar to Python's decorators; the important part is that, differently from the private
and protected
methods, this decorator-like method should define a method_added
that undefines itself:
class Module
def simple_decorator
eigenclass = class << self; self; end
eigenclass.class_eval do
define_method :method_added do |name|
eigenclass.class_eval { remove_method :method_added }
old_name = 'old_' + name.to_s
alias_method old_name, name
class_eval %Q{
def #{name}(*args, &block)
p 'Do something before call...'
#{old_name}(*args, &block)
p '... and something after call.'
end
}
end
end
end
end
class UsefulClass
simple_decorator
def print_something
p "I'm a decorated method :)"
end
def print_something_else
p "I'm not decorated :("
end
end
a = UsefulClass.new
a.print_something
a.print_something_else
simple_decorator
looks like a language keyword and behaves like private
; however, because it removes the method_added
hook, it only applies to the immediately following method definition.