Jeremy W. wrote in post #1059759:
On 6 May 2012 22:13, Guillem V. [email protected] wrote:
You could just reopen ActiveRecord::Base. Create a new initializer (a
http://www.ihid.co.uk
end
end
OK, so two more suggestions:
- Use an after_initialize block in your config (
Configuring Rails Applications — Ruby on Rails Guides)
to call your method_creation code.
- 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|
self.class.send(:define_method,
“#{association.name.to_s}_tokens=”) do |value|
write_attribute(method, self.another_custom_method)
end
#more stuff
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.