Skip to content

Instantly share code, notes, and snippets.

@subhashb
Created March 12, 2013 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subhashb/5143172 to your computer and use it in GitHub Desktop.
Save subhashb/5143172 to your computer and use it in GitHub Desktop.
Defining Dynamic Method and passing model as argument
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