Re: [Rails] meta-programming 101
On Sun, Oct 10, 2010 at 9:16 AM, Rajinder Yadav <devguy.ca@gmail.com> 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
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home