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

    • DennisBB: @neo I don’t see where he wrote on his site that he’ll provide support for that program
    • DennisBB: That’s kool d00d Haven’t tried it yet, but once I’ll have time
    • Pedro: Please send me an invite ;)
    • Josh: That would be sweet. This is the only thing I can find anywhere that actually updates MySpace status outside of...
    • fernyb: @josh I haven’t worked on this code for a while but I suppose I can take a quick look at it, of course...

    Recent Listened to Tracks

    Loading...


My blog is worth $1,693.62.
How much is your blog worth?


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

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