Created
March 12, 2013 14:11
-
-
Save subhashb/5143172 to your computer and use it in GitHub Desktop.
Defining Dynamic Method and passing model as argument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person | |
attr_accessor :firstname | |
attr_accessor :age | |
end | |
class Object | |
def metaclass | |
class << self; self; end | |
end | |
end | |
class Main | |
def create_method | |
metaclass.instance_eval do | |
define_method :print_my_data do |person| | |
p "My name is #{person.firstname}" | |
p "My age is #{person.age}" | |
end | |
end | |
end | |
end | |
p1 = Person.new | |
p1.firstname = 'Subhash' | |
p1.age = 30 | |
p2 = Person.new | |
p2.firstname = 'Sumedha' | |
p2.age = 23 | |
m = Main.new | |
m.create_method | |
m.print_my_data(p1) | |
m.print_my_data(p2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment