我具有模塊助手中的所有常用功能。這些函數只有在包含一個基於每個項目的動態常量文件時才能起作用。現在,重用模塊的最佳方法是什麼?導軌中的通用模塊
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
我想這會更好理解!
我強烈建議不要在Rails應用程序中調用模塊'Helper',因爲helpers已經在Rails上下文中有特定的含義。 Rails中的Helpers是自動加載到視圖和/或控制器中的功能。 – max