3

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

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

我在自定义验证器中使用它,我必须验证上传图像的大小。我希望能够不仅在这个模型中使用这种数据结构,而且在任何地方都能使用。在我所有的模型、视图和控制器中。

我将如何去做,我会把它放在哪里?

4

2 回答 2

2

我会使用一个模块

把它放在你的lib目录中。(您可能需要将 Rails 3 配置为从您的lib文件夹中自动加载类和模块。请参阅此问题。)

# 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.

于 2013-04-10T00:14:16.620 回答
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.

于 2013-04-10T01:02:21.317 回答