Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'd like to add something about their <em>keyword-like</em> behavior, because the answers have been more about <em>where</em> than <em>how</em>; the answer lies in the complex metaprogramming capabilities of Ruby. It is possible to use them as <em>keywords</em> making use of the <code>method_added</code> 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 <code>method_added</code> hook receives as his argument the name of the method that has been defined: this way, it's possible to modify it's behavior.</p> <p>For example, you could use this hook to define a behavior similar to Python's <em>decorators</em>; the important part is that, differently from the <code>private</code> and <code>protected</code> methods, this decorator-like method should define a <code>method_added</code> that undefines itself:</p> <pre><code>class Module def simple_decorator eigenclass = class &lt;&lt; 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, &amp;block) p 'Do something before call...' #{old_name}(*args, &amp;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 </code></pre> <p><code>simple_decorator</code> looks like a language keyword and behaves like <code>private</code>; however, because it removes the <code>method_added</code> hook, it only applies to the immediately following method definition.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload