Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A lot of the magic you see in Rubyland has to do with metaprogramming, which is simply writing code that writes code for you. Ruby's <code>attr_accessor</code>, <code>attr_reader</code>, and <code>attr_writer</code> are all simple metaprogramming, in that they create two methods in one line, following a standard pattern. Rails does a whole lot of metaprogramming with their relationship-management methods like <code>has_one</code> and <code>belongs_to</code>.</p> <p>But it's pretty simple to create your own metaprogramming tricks using <code>class_eval</code> to execute dynamically-written code.</p> <p>The following example allows a wrapper object to forwards certain methods along to an internal object:</p> <pre><code>class Wrapper attr_accessor :internal def self.forwards(*methods) methods.each do |method| define_method method do |*arguments, &amp;block| internal.send method, *arguments, &amp;block end end end forwards :to_i, :length, :split end w = Wrapper.new w.internal = "12 13 14" w.to_i # =&gt; 12 w.length # =&gt; 8 w.split('1') # =&gt; ["", "2 ", "3 ", "4"] </code></pre> <p>The method <code>Wrapper.forwards</code> takes symbols for the names of methods and stores them in the <code>methods</code> array. Then, for each of those given, we use <code>define_method</code> to create a new method whose job it is to send the message along, including all arguments and blocks.</p> <p>A great resource for metaprogramming issues is <a href="http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html" rel="noreferrer">Why the Lucky Stiff's "Seeing Metaprogramming Clearly"</a>.</p>
 

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