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( :D ell)
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

    • Ahmed: @fernyb.. Thanks man! I forked the project, but I am newbie in open source, and don’t know where to...
    • fernyb: @Ahmed, yeah you can help. It’s hosted on (http://github.com/fernyb/Cupc ake) so you can also fork it...
    • Ahmed: And hey! Can I help with your new PHP framework? plssssssssss :( (
    • Ahmed: hmmmmm I just wanna ask you about something… did you ever create API for Craigslist? I am thinking of...
    • Matt James: Same here… amazing project that I have been very happily using for a while. Sadly it seems to be...

    Recent Listened to Tracks

    Loading...

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

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