Ruby on Rails
Thursday, November 13, 2014
(In the final code sample, the error I get is:
-- NameError (undefined local variable or method `award_callback' for #<Post:0x002b57c04d52e0>):
On Thursday, November 13, 2014 8:37:40 PM UTC-8, Debajit Adhikary wrote:
On Thursday, November 13, 2014 8:37:40 PM UTC-8, Debajit Adhikary wrote:
I have the following classes:class AwardBaseclass AwardOne < AwardBaseclass Post < ActiveRecord::BaseThe Post is an ActiveRecord, and the Award has a can_award? class method which takes a post object and checks to see if it meets some criteria. If yes, it updates post.owner.awards.I know I can do this using an Observer pattern (I tested it and the code works fine). However, that requires me to add additional code to the model. I'd like not to touch the model at all if possible. What I'd like to do is run the Award checks like this (the trigger will be invoked at class load time):class AwardOne < AwardBasetrigger :post, :after_savedef self.can_award?(post)...endendThe intention with the above code is that it should automatically add AwardOne.can_award? to Post's after_save methodSo essentially what I'm trying to do is to get the above code to be equivalent to:class Post < ActiveRecord::Baseafter_save AwardOne.can_award?(self)...endwhich is basically:class Post < ActiveRecord::Baseafter_save :check_awarddef check_awardAwardOne.can_award?(self)endendHow can I do this without modifying the Post class?---------------------------------- Here's what I've done (which does not appear to work):class AwardBasedef self.trigger (klass, active_record_event)model_class = klass.to_classthis = selfmodel_class.instance_eval dodef award_callbackthis.can_award?(self)endendmodel_class.class_eval doself.send(active_record_event, :award_callback)endenddef self.can_award? (model)raise NotImplementedErrorendend
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/303ca1b9-15f0-478f-9d69-1a25ddadca01%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment