代码之家  ›  专栏  ›  技术社区  ›  user1913545

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

  •  -1
  • user1913545  · 技术社区  · 7 年前

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

    以下是我的方法:

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

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   ian    7 年前
    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说从其他地方加载数据是正确的。