Loading ...
Sorry, an error occurred while loading the content.

70Re: [ruby-india] Re: Learning Ruby

Expand Messages
  • Yogi
    Mar 6, 2005
    • 0 Attachment
      > whoa !! ruby has macros ? news to me!! some references please ?

      Ruby's eval and class_eval methods provides support for macros e.g.
      the attr_reader, attr_writer and attr_accessor are macros that
      generate getter/setter methods and instance variables for each symbol
      passed to them.

      So the foll code:
      class Foo
      attr_reader :bar
      end

      will allow you to do:
      f = Foo.new
      f.bar = "x"
      puts f.bar

      Heres an example from the activesupport lib (thats used by rails)
      which creates class-level attributes similar to the attr* methods:

      # Extends the class object with class and instance accessors for class
      attributes,
      # just like the native attr* accessors for instance attributes.
      class Class # :nodoc:
      def cattr_reader(*syms)
      syms.each do |sym|
      class_eval <<-EOS
      if ! defined? @@#{sym.id2name}
      @@#{sym.id2name} = nil
      end

      def self.#{sym.id2name}
      @@#{sym}
      end

      def #{sym.id2name}
      @@#{sym}
      end

      def call_#{sym.id2name}
      case @@#{sym.id2name}
      when Symbol then send(@@#{sym})
      when Proc then @@#{sym}.call(self)
      when String then @@#{sym}
      else nil
      end
      end
      EOS
      end
      end

      def cattr_writer(*syms)
      syms.each do |sym|
      class_eval <<-EOS
      if ! defined? @@#{sym.id2name}
      @@#{sym.id2name} = nil
      end

      def self.#{sym.id2name}=(obj)
      @@#{sym.id2name} = obj
      end

      def self.set_#{sym.id2name}(obj)
      @@#{sym.id2name} = obj
      end

      def #{sym.id2name}=(obj)
      @@#{sym} = obj
      end
      EOS
      end
      end
    • Show all 12 messages in this topic