meta-programming 101

how can I get the following to work, what am I not understanding about how modules work?

module MakeMethod     def self.make_method( name )        define_method( name ) do |count|           puts "you called method #{name.to_s}"           puts "the count is #{count}"        end     end end

class Person

    include MakeMethod

    make_method :hello     make_method :bye

    def initialize( name )        @name = name     end

    def greet        puts "Hello! I'm #{@name}"     end

end

i realized i posted to the rails thread instead of the ruby thread =P still if someone can please answer this, thanks!

there are many ways, but i usually start as simple as possible, creating modules by fxn. classes simple as possible

# we have module that defines method module MakeMethod   def make_method( name )      define_method( name ) do |count|         puts "you called method #{name.to_s}"         puts "the count is #{count}"      end   end end

# we have module that modifies a class and creates corr methods module MethodMaker   class << self     include MakeMethod   end

  make_method :hello   make_method :bye

end

# we create class, as simple as possible class Person

  def initialize( name )      @name = name   end

  def greet      puts "Hello! I'm #{@name}"   end

end

# we create person class. it works j=Person.new "rajin"

# but hello method does not work yet since we've not defined it yet on person class # j.hello 1 => will err here

# now we modify person class Person   include MethodMaker end

# the new methods now work j.hello 1 j.bye 1

best regards -botp

what i would like to do is be able to use make_method from class Person, like:

class Person    include MethodMaker

   make_method :hello    make_method :bye

end

You should read about the difference between `include' and `extend' keywords.

module MakeMethod     def make_method( name )        define_method( name ) do |count|           puts "you called method #{name.to_s}"           puts "the count is #{count}"        end     end end

class Person     extend MakeMethod     make_method :hello end

Robert Pankowecki

Thanks Robert for pointing this out!