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

Where can I store a mapping method?

我使用 Sinatra 框架开发应用程序。我会知道最好的地方是存储映射方法:在控制器或装饰器中。事实上,我从一个有法国领土的法国网站导入数据,我想将数字领土从数字转换为名称。

这是我的方法:

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

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

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 说从其他地方加载它是正确的。