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

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


我在自定义验证器中使用此代码,我必须验证上传的图像的大小。我希望不仅可以在这个模型中使用这种数据结构,还可以在任何地方使用。在我所有的模型,视图和控制器中。

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

最佳答案

我会使用一个模块。

将其粘贴在您的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

10-07 21:17
查看更多