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

问题描述 投票:-1回答:1

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

这是我的方法:

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

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

ruby sinatra
1个回答
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说是从其他地方加载它是正确的。

© www.soinside.com 2019 - 2024. All rights reserved.