Reputation: 350
I have a data structure like this in one of my models:
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
I use this in a custom validator I have to validate the sizes of images uploaded. I would like to be able to use this data structure not just in this one model - but everywhere. In all my models, views and controllers.
How would I go about doing that, where would I put it?
Upvotes: 3
Views: 262
Reputation: 29599
Another option is to create an initializer file and declare a constant there.
# 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}
}
Then in your model or controller, just use IMAGE_SIZE_LIMITS['web']['maxheight']
to get 480
.
Upvotes: 2
Reputation: 6682
I would use a module.
Stick it in your lib
directory. (You may need to configure Rails 3 to autoload classes and modules from your lib
folder. See 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
Then in your models or controllers:
class MyModel < ActiveRecord::Base
include ImageSizes
# ...
end
class MyController < ApplicationController
include ImageSizes
# ...
end
Now, each model or controller that includes the ImageSizes
module will have access to the module's methods, namely image_size_limits
.
Upvotes: 2