2015-06-25 35 views
1

我具有模塊助手中的所有常用功能。這些函數只有在包含一個基於每個項目的動態常量文件時才能起作用。現在,重用模塊的最佳方法是什麼?導軌中的通用模塊

module Helper 
    #dunno how to include the constants file and reuse it 
    def morning_food(who) 
    puts FOOD_HABIT[:morning] 
    end 
end 

../Constant文件

module Animal 
module Constants 
FOOD_HABIT = { 
    morning: "a", 
    ... 
} 
end 
end 

module Person 
module Constants 
FOOD_HABIT = { 
    morning: "dosa", 
    ... 
} 
end 
end 

一個更好的例子:我想建立一個定製的複雜查詢生成的寶石,可以在多個項目中重複使用!因此,除了用戶選擇的過濾器之外,我們可以爲每個項目設置不同的度量值的默認過濾器值!那些默認常量將在一個常量文件中。現在我想在每個項目中重新使用助手方法。

module QueryBuilder 
module Helper 
    #include the constants file dynamically! 
    def default_value(metrics) 
    # fetch and return the values 
    end 
end 
end 

.. /constants files 
module ProjectX 
module Query 
    module Constants 
    DEFAULT_VALUES = { 
    } 
    end 
end 
end 



module ProjectY 
module Query 
    module Constants 
    DEFAULT_VALUES = { 
    } 
    end 
end 
end 

我想這會更好理解!

+1

我強烈建議不要在Rails應用程序中調用模塊'Helper',因爲helpers已經在Rails上下文中有特定的含義。 Rails中的Helpers是自動加載到視圖和/或控制器中的功能。 – max

回答

0

您需要將模塊擴展到需要的地方。如果你需要它的類,然後使用include

module Animal 
module Constants 
    extend Helper 
+0

這使'morning_food'成爲'Constants'的一個模塊方法,這在這裏有點不合理。 – mudasobwa

+0

我會說OP的整個例子都是無稽之談。 – max

0
module Helper 
    #dunno how to include the constants file and reuse it 
    def morning_food 
    puts self.class.const_get('Constants::FOOD_HABIT')[:morning] 
    end 
end 

class Animal 
module Constants 
    FOOD_HABIT = { 
    morning: "a", 
    } 
end 
include Helper 
end 

class Person 
module Constants 
    FOOD_HABIT = { 
    morning: "dosa", 
    } 
end 
include Helper 
end 

Person.new.morning_food 
#⇒ "dosa" 
0

對我來說,它看起來像你應該創建一個域對象(即反映了現實世界名詞的對象)。

動物和人的共享功能,我猜測會有更多的共享功能。

因此,一個好的方法是使用繼承,並簡單地將Person/Animal對象傳遞給飲食習慣的選項散列。

class Organism 

    attr_accessor :morning, :evening #etc.. 

    def initialize(options={}) 
    options.each do |attribute, value| 
     self.send "#{attribute}=", value 
    end 
    end 

end 

class Person < Organism 

    # Person methods 

end 

class Animal < Organism 

    # Animal methods 

end