Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby Metaprogramming

Ruby Metaprogramming

Slides from my talk at #codemotion #es (Madrid, March 24th 2012).

http://codemotion.es/

Sergio Gil

March 25, 2012
Tweet

More Decks by Sergio Gil

Other Decks in Programming

Transcript

  1. >> str = "hola" => "hola" >> str.methods => [...,

    :reverse, ...] >> def str.reverse "adios" end
  2. >> str = "hola" => "hola" >> str.methods => [...,

    :reverse, ...] >> def str.reverse "adios" end >> str.reverse
  3. >> str = "hola" => "hola" >> str.methods => [...,

    :reverse, ...] >> def str.reverse "adios" end >> str.reverse => "adios"
  4. class Company def projects get('/projects') end def people get('/people') end

    ... private def get(url) HTTP::Request.new(url).get end end
  5. class Company [:projects, :people, ...].each do |method| eval %Q{ def

    #{method} HTTP::Request.new('/#{method}').get end } end end
  6. module HTTP def get(*methods) methods.each do |method| define_method method do

    HTTP::Request.new("/#{method}").get end end end end
  7. module HTTP def get(*methods) methods.each do |method| define_method method do

    HTTP::Request.new("/#{method}").get end end end end class Company extend HTTP get :projects, :people, ... end
  8. “Cleverness cannot win. The only weapons we have are simplicity

    and convention” http://alarmingdevelopment.org/?p=422