Dynamic Method Creation


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. # since define_method is private, we will abstract it into a public method named create_method
  2. # so that we can just use Object#create_method when we want to dynamically create methods
  3. # Now you can do something like
  4. # ["one","two","three"].each { |n| Model.create_method("number_#{n}") { puts n }}
  5. # Now you have :
  6. # Model.number_one # => one
  7. # Model.number_two # => two
  8. # Model.number_three # => three
  9. def create_method(name,&block)
  10. self.class.send(:define_method,name,&block)
  11. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.