Ruby Technique: Meta Programming

Posted in Programming, Ruby on Mar 02, 2008

Meta Programming is code that writes code. See the code sample below.
I have made a screencast of this process. View it here

#!/usr/bin/env ruby

class Product
  def initialize(items)
    items.each {|item| Product.product(item) }
  end

  def self.product(item)
    code = %Q{
      def add_#{item}(item)
        @#{item} = [] unless @#{item}
        @#{item} << item
      end

      def display_#{item}s
        @#{item}.each {|item| puts item }
      end
    }
    class_eval(code)
  end
end

class Item < Product
  def initialize(*items)
    super(items)
  end
end

cart = Item.new(:book, :computer, :music)
cart.add_book(:Ruby) # => Add a book to our cart items

cart.display_books # => We want to display All books we have added
puts "\n"

cart.add_computer(:Apple)
cart.add_computer(:Dell)
cart.add_computer(:Sony)
cart.display_computers # => Display All Computers
puts "\n"

cart.add_music(’Modest Mouse‘)
cart.add_music(’Northstar‘)
cart.display_musics # => Display All Music Items

Trackback URI | Comments RSS

Leave a Reply

  • Recent Comments

    • wat: hey fernyb i was just informed that the new pwnage tool is releasing tomrow with installer 4 and the updated...
    • Gaisce1: Fernando, Would it be possible to have the ‘current track’ title displayed in LastBridge as well...
    • Pip: Even after using TextWrangler and inputting my last.fm username there VLC gives me this error message: main: no...
    • Pip: I can give you a call from my phone, if you don’t mind providing some live help. I have copied the file as...
    • Pip: Thanks Fernando for your prompt reply! I am glad you are also a Mac user, but I have to confess that your blog...

Bad Behavior has blocked 246 access attempts in the last 7 days.

eastern-avalanche
eastern-avalanche
eastern-avalanche
eastern-avalanche