我在哪里可以存储映射方法?

时间:2018-02-28 21:10:24

标签: ruby sinatra

我使用Sinatra框架处理应用程序。我知道存储映射方法的最佳位置:在控制器或装饰器中。事实上,我从具有法国领土的法国网站导入数据,我想将数字区域从数字转换为名称。

这是我的方法:

def territory_mapping(code)
  {
    '01' => 'Auvergne-Rhône-Alpes',
    '02' => 'Hauts-de-France',
    '03' => 'Auvergne-Rhône-Alpes'
  }[code]
end

我想知道在哪里可以存储此方法。

1 个答案:

答案 0 :(得分:0)

begin
  case "my hash's use" do
    when "it's for display" then
      if "it's a small method"
        "put it in a helper for use a controller"
      else
        "put it in a module and include it using via `helper`"
      end
    when "it's not for display" then "put it in a helper for use in a route block"
  else
    "it should go in the class that requires it."
  end

rescue NoMethodError => e
  e.message = <<~MESSAGE
    If it doesn't work because the logic isn't defined
    in your views or route blocks then it should go in 
    the class that requires it."
  MESSAGE
ensure
  "I get out more so I stop answering this question in Ruby ;-)"
end

换句话说,把它放在帮助器中然后你可以稍后评估它是否应该去其他地方。

无论如何,@ tadman对于将示例哈希声明为常量是正确的,你应该像对待任何其他常量一样处理对它的访问 - 如果你需要在多个地方使用它,那么在命名空间中将它放在上面的级别层次结构。如果它有很多数据,那么@Stefan说从其他地方加载它是正确的。

相关问题