rails

时间:2015-06-25 10:09:07

标签: ruby-on-rails ruby ruby-on-rails-3

我在模块助手中有所有常用功能。只有当它包含一个基于每个项目动态的常量文件时,这些函数才会起作用。现在,重用模块的最佳方法是什么?

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

../常量文件

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

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

一个更好的例子:我想构建一个可以在多个项目中重用的自定义复杂查询生成器gem!因此,除了用户选择的过滤器之外,我们可以为每个项目提供不同的默认过滤器值!那些默认常量将在常量文件中。现在我想在每个项目中重用helper方法。

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 

我想这会更有意义!

3 个答案:

答案 0 :(得分:0)

您需要在需要它的模块中扩展模块。如果您在课堂上需要它,请使用include

module Animal
 module Constants
   extend Helper

答案 1 :(得分: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"

答案 2 :(得分: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