{"maxheight" => 480, "maxwidth" => 680-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 06:25:03 27 4
gpt4 key购买 nike

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

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

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

我该怎么做,我应该把它放在哪里?

最佳答案

我会使用模块

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

然后在您的模型或 Controller 中:

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


class MyController < ApplicationController
include ImageSizes
# ...
end

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

关于ruby-on-rails - 在 Rails 中存储全局共享数据结构的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15914621/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com