Rails Metaprogramming: How to add instance methods at runtime?

Posted by Larry K on Stack Overflow See other posts from Stack Overflow or by Larry K
Published on 2010-03-29T18:03:13Z Indexed on 2010/03/29 18:53 UTC
Read the original article Hit count: 255

Filed under:
|
|

I'm defining my own AR class in Rails that will include dynamically created instance methods for user fields 0-9. The user fields are not stored in the db directly, they'll be serialized together since they'll be used infrequently. Is the following the best way to do this? Alternatives?

Where should the start up code for adding the methods be called from?

class Info < ActiveRecord::Base

end

# called from an init file to add the instance methods
parts = []
(0..9).each do |i|
   parts.push "def user_field_#{i}"     # def user_field_0
   parts.push   "get_user_fields && @user_fields[#{i}]"
   parts.push "end"
end

Info.class_eval parts.join

© Stack Overflow or respective owner

Related posts about ruby

Related posts about rails