ruby on rails - Modifying an ActiveRecord module to work with any model -


so while ago created small module serve methods need votable polymorphic association, , while meant used activerecord want use mongo, , since i'm using mongoid of methods associations need create in intance have same names , everthing here take @ previous code:

# config/initializers/acts_as_votable.rb  module actsasvotable  end  module activerecord   class base     class << self       cattr_accessor :votable        def acts_as_votable         has_many :votes, :as => :voteable       end        def acts_as_voter         has_many :votes, :as => :voter       end        def votable?         method_defined? :votes       end     end      def votable?       self.class.send(:method_defined?, :votes)     end   end end 

and here how used:

class recipe < activerecord::base   acts_as_votable   # more stuff... end 

so you'll notice 2 issues here, firstly, i'm extending activerecord::base, how can make work model, not ones inherit activerecord?, secondly need empty module actsasvotable one? doing wrong here?

if put code module actsasvotable, shouldn't able call includes actsasvotable model?

first, put in initializer or in /lib sure path loaded in application.

module actsasvotable    extend activesupport::concern    module instancemethods     def votable?       self.class.send(:method_defined?, :votes)     end   end    module classmethods     cattr_accessor :votable      def acts_as_votable       has_many :votes, :as => :voteable     end      def acts_as_voter       has_many :votes, :as => :voter     end      def votable?       method_defined? :votes     end    end end 

then in model:

class user < activerecord::base    include actsasvotable  end 

finally:

user.methods.include?("acts_as_votable") # => true 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -