【问题标题】:Where can I store a mapping method?我在哪里可以存储映射方法?
【发布时间】:2018-03-03 04:09:13
【问题描述】:

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

这是我的方法:

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

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

【问题讨论】:

  • 这取决于上下文和复杂性。你能把代码作为例子吗?
  • 我添加了示例。
  • 尝试将这样的固定哈希声明为常量,这样您就不需要在每次执行该方法时都创建新对象(和垃圾!)。那只是一个查找表。如果您的 Sinatra 应用程序只是一个文件,您可以将它放在您喜欢的任何位置。如果它有多个文件,那么它的去向取决于您,Sinatra 没有像 Rails 那样的特定约定。
  • 你怎么知道这个地方?
  • 您的业务逻辑是否只需要在一个控制器/一个类中使用此哈希?如果是这样,只需将哈希作为常量放入该文件中

标签: ruby sinatra


【解决方案1】:
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 说从其他地方加载它是对的。

【讨论】:

  • 分支可以更紧密也让我很开心:-D
猜你喜欢
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
相关资源
最近更新 更多