2009-10-05 32 views
5

我在包含某些模型的引擎樣式插件中添加了一些代碼。在我的應用程序中,我想擴展其中的一個模型。我設法通過在初始化程序中包含模塊,將實例和類方法添加到相關模型中。使用模塊在「has_many」插件中擴展模型

然而,我似乎無法添加關聯,回調等我得到'方法未找到'的錯誤。

/libs/qwerty/core.rb

module Qwerty 
    module Core 
    module Extensions 

     module User 
     # Instance Methods Go Here 

     # Class Methods 
     module ClassMethods 
      has_many :hits, :uniq => true # no method found 

      before_validation_on_create :generate_code # no method found 

      def something # works! 
      "something" 
      end 
     end 

     def self.included(base) 
      base.extend(ClassMethods) 
     end 
     end 
    end 
    end 
end 

/initializers/qwerty.rb

require 'qwerty/core/user' 

User.send :include, Qwerty::Core::Extensions::User 

回答

6

我認爲這應該工作

module Qwerty 
    module Core 
    module Extensions 
     module User 
     # Instance Methods Go Here 

     # Class Methods 
     module ClassMethods 
      def relate 
      has_many :hits, :uniq => true # no method found 

      before_validation_on_create :generate_code # no method found 
      end 

      def something # works! 
      "something" 
      end 
     end 

     def self.included(base) 
      base.extend(ClassMethods).relate 
     end 
     end 
    end 
    end 
end 

舊的代碼是錯誤的原因驗證和關聯在模塊加載時被調用,而且這個模塊對ActiveRecord一無所知。這是Ruby的一個普遍方面,在加載時直接調用類或模塊體內的代碼。你不想那樣。爲了解決這個問題,你可以使用上面的解決方案。

+0

問題:在做'重新加載!'時在控制檯中,類會重新加載,但由於模塊(在我的情況下)是從初始化程序調用的,因此該模塊不會重新應用。 – Kris 2009-10-07 11:07:24

+0

此外,目前看來,只有在使用控制檯時,模塊中的代碼纔會被包含,當從控制器調用相同的代碼時,它會失敗。我想發佈一個代碼示例,但答案似乎不正確(畢竟這不是一個論壇)... – Kris 2009-10-07 11:09:15

+0

CONTROLLER:render:text => User.new.respond_to?('hits')並返回# => false CONSOLE:User.new.respond_to?('hits')#=> true PREEMPT:我重新啓動了服務器:) – Kris 2009-10-07 11:15:23

14

你應該可以做到這一點。更簡潔一點的恕我直言。

module Qwerty::Core::Extensions::User 
    def self.included(base) 
    base.class_eval do 
     has_many :hits, :uniq => true 
     before_validation_on_create :generate_code 
    end 
    end 
end 
+0

這完全是正確答案。 – kikito 2012-06-19 09:38:23

4

在Rails 3,這聽起來像一個良好的用例的ActiveSupport ::關注:

module Qwerty::Core::Extensions::User 

    extend ActiveSupport::Concern 

    included do 
    has_many :hits, :uniq => true 
    before_validation_on_create :generate_code 
    end 
end 

class User 
    include Querty::Core::Extensions::User 
    # ... 
end 

這裏是ActiveSupport::Concern docs並在其上最有用的blog article我發現。