Re: [Rails] Re: run script after initialize
On 6 May 2012 22:13, Guillem Vidal <lists@ruby-forum.com> wrote:
Jeremy Walker wrote in post #1059748:
>> ActiveRecord::Base.send(:descendants) andNot in my case. What I want to do is define different method names
>> ActiveRecord::Base.send(:subclasses) is allways empty [].
>>
>> I've tried it on config/environment.rb and config/application.rb with no
>> success, can someone tell me what i can do about it?
>>
>
> You could just reopen ActiveRecord::Base. Create a new initializer (a
> ruby file in config/initializers) with:
>
> class ActiveRecord::Base
> def new_method
> # do stuff
> end
> end
>
> Does that help?
> Jeremy Walker
> http://www.ihid.co.uk
depending on its relation, for example:
subclass.reflect_on_all_associations.each do |association|
ActiveRecord::Base.send(:descendants).each do |subclass|
macro = association.macro #:has_one, :has_many...
subclass.send(:define_method, "#{association.name}_tokens") do
read_attribute(__method__[0..-8])
end
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?
--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home