我的一个模型中有这样的数据结构:
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
我在自定义验证器中使用它我必须验证上传图像的大小。我希望能够在这个模型中使用这种数据结构 - 但是无处不在。在我的所有模型,视图和控制器中。
我将如何做到这一点,我会把它放在哪里?
答案 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
。