Jeremy Walker wrote in post #1059759: > On 6 May 2012 22:13, Guillem Vidal <li...@ruby-forum.com> wrote: > >> > You could just reopen ActiveRecord::Base. Create a new initializer (a >> > http://www.ihid.co.uk >> end >> end >> > > OK, so two more suggestions: > 1) Use an after_initialize block in your config ( > http://guides.rubyonrails.org/configuring.html#rails-general-configuration) > to call your method_creation code. > 2) Re-open the class (as per my prev suggestion) but write a > create_association_tokens method that contains the code to define your > reflected methods, and use ActiveRecord::Base's after_initialize method > to > call that method on an object, thus creating your methods on an > object-by-object basis, rather than for the class. > > I'm intrigued by the point of all this?
Sorry about the delay, I couldn't access to a computer since now :(. Done it, but it raises me an error because i have a attr_writer, i need to initialize the method. module MyModule def self.included(base) base.send(:extend, InstanceMethods) base.send(:after_initialize, :set_reader_writer_tokens) end module InstanceMethods def set_reader_writer_tokens class.reflect_on_all_associations.each do |association| class.send(:define_method,"#{association.name.to_s}_tokens") do attribute(__method__) end self.class.send(:define_method, "#{association.name.to_s}_tokens=") do |value| write_attribute(__method__, self.another_custom_method) end end end end ActiveRecord::Base.send(:include, MyModule) Loading development environment (Rails 3.2.2) class OptionType < ActiveRecord::Base belongs_to :type end OptionType.new(:type_tokens => "ba,b") raises an unknown attribute :type_tokens. But if I first initialize the record withouth accessing to the attribute: > OptionType.new => #<OptionType ...> > OptionType.new(:type_tokens => "ba,b") => #<OptionType id: nil, name: nil, presentation: nil, created_at: nil, updated_at: nil> Then I can done it. The problem is that I need to set up that attribute before the initialitzation of the class. Is a very good approach, but still not enogh for a ruby on rails application. Maybe it can be done using method_missing... but I'm a little bit scared of overwriting activerecord method_missing, also it's not clear. -- Posted via http://www.ruby-forum.com/. -- 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+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.