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


Kind Regards,
Rajinder Y.

On 10-10-09 09:16 PM, Rajinder Y. wrote:

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

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


Kind Regards,
Rajinder Y.

On Sun, Oct 10, 2010 at 9:16 AM, Rajinder Y. [email protected]
wrote:

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

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

On 10-10-09 10:50 PM, botp wrote:

  define_method( name ) do |count|

end
def initialize( name )
j=Person.new “rajin”

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


Kind Regards,
Rajinder Y.

You should read about the difference between include' andextend’
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

On 10-10-10 03:45 AM, Robert Pankowecki (rupert) wrote:

end

class Person
extend MakeMethod
make_method :hello
end

Robert Pankowecki

Thanks Robert for pointing this out!


Kind Regards,
Rajinder Y.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs