在Rails中存储全局共享数据结构的位置

时间:2013-04-09 23:58:43

标签: ruby-on-rails ruby-on-rails-3.2

我的一个模型中有这样的数据结构:

def image_size_limits
    {
        "web" => {"maxheight" => 480, "maxwidth" => 680, "minheight" => 400, "minwidth" => 600}, 
        "phone" => {"height" => 345, "width" => 230, "minheight" => 300, "minwidth" => 200},
        "tablet" => {"height" => 680, "width" => 480, "minheight" => 600, "minwidth" => 400},
        "other" => {"height" => 680, "width" => 480, "minheight" => 600, "minwidth" => 400}
    }
end

我在自定义验证器中使用它我必须验证上传图像的大小。我希望能够在这个模型中使用这种数据结构 - 但是无处不在。在我的所有模型,视图和控制器中。

我将如何做到这一点,我会把它放在哪里?

2 个答案:

答案 0 :(得分:2)

我会使用模块

将其粘贴在lib目录中。 (您可能需要将Rails 3配置为从lib文件夹中自动加载类和模块。请参阅this question

# lib/image_sizes.rb

module ImageSizes
  def image_size_limits
    {
      "web" => {"maxheight" => 480, "maxwidth" => 680, "minheight" => 400, "minwidth" => 600}, 
      "phone" => {"height" => 345, "width" => 230, "minheight" => 300, "minwidth" => 200},
      "tablet" => {"height" => 680, "width" => 480, "minheight" => 600, "minwidth" => 400},
      "other" => {"height" => 680, "width" => 480, "minheight" => 600, "minwidth" => 400}
    }
  end
end

然后在您的模型或控制器中:

class MyModel < ActiveRecord::Base
  include ImageSizes
  # ...
end


class MyController < ApplicationController
  include ImageSizes
  # ...
end

现在,包含ImageSizes模块的每个模型或控制器都可以访问模块的方法,即image_size_limits

答案 1 :(得分:2)

另一个选择是创建一个初始化文件并在那里声明一个常量。

# config/initializers/image_size_limits.rb

IMAGE_SIZE_LIMITS = {
  "web" => {"maxheight" => 480, "maxwidth" => 680, "minheight" => 400, "minwidth" => 600}, 
  "phone" => {"height" => 345, "width" => 230, "minheight" => 300, "minwidth" => 200},
  "tablet" => {"height" => 680, "width" => 480, "minheight" => 600, "minwidth" => 400},
  "other" => {"height" => 680, "width" => 480, "minheight" => 600, "minwidth" => 400}
}

然后在您的模型或控制器中,只需使用IMAGE_SIZE_LIMITS['web']['maxheight']获取480