2013-05-31 17 views
1

我使用ActiveSupport :: Concern來幹掉我的AR類中包含的一些代碼。我有一個模塊,用於計算下威爾遜結合在數據:ActiveSupport ::關注和類方法

module CalculateWilsonBound 
    extend ActiveSupport::Concern 

    included do 
     class_attribute :wilson_ratings 
     class_attribute :wilson_positive_ratings 
    end 

    def calculate_wilson_lower_bound 
     number_of_ratings = self.class.wilson_ratings.call(self) 
     ... 
    end 

end 

後我已經包括它到物體上,我想提供兩級電平的方法,其定義塊這將返回各自的(wilson_ratings,wilson_positive_ratings)計數。

從視圖中的AR對象點:

class Influence < ActiveRecord::Base 
    include CalculateWilsonBound 

    wilson_ratings { |model| model.votes } 
    wilson_positive_ratings { |model| model.positive_votes } 

這不會造成任何運行時錯誤,但是當我訪問類屬性:

number_of_ratings = self.class.wilson_ratings.call(self) 

這是

首先,我組織的代碼是有道理的,secondaly,爲什麼是類屬性爲零?

回答

2

我相信你需要做:

class Influence < ActiveRecord::Base 
    include CalculateWilsonBound 

    self.wilson_ratings = Proc.new { |model| model.votes } 
    self.wilson_positive_ratings = Proc.new { |model| model.positive_votes } 
end 

此刻的你有2個問題。

  1. 當試圖在一個類定義了Rails的情況下分配一個類屬性將不知道你指的是類屬性,除非您使用self.

  2. 你需要指定class屬性,而不是傳入一個塊。當你的代碼現在看起來像你正在調用一個方法wilson_ratings並傳遞一個塊。

至於你的代碼是否合理,它開始對我有點有趣。我更喜歡服務類模式(請參閱http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/) - 它可以防止您不得不亂用class_attributes和其他潛在的多毛概念。

0

如果你想class屬性調用,您可以將其指定一個進程

self.wilson_ratings = proc{ |model| model.votes } 
相關問題