Proper place to define variables used by my erb templates + layouts for HTML styles?

StackOverflow https://stackoverflow.com/questions/1098867

  •  11-09-2019
  •  | 
  •  

Question

I have a local variable in an erb template:

<% thumbnail_width = 50 %>

I'm using this for sizing some thumbnail images.

But now I realize that a number of templates will need to access this variable.

Where should I move it to and what type of variable should it be?

Was it helpful?

Solution

There are several solutions, depending on how this variable interacts with the Rails environment.

Configurations

You can use a global configuration file (see for example SimpleConfig plugin). This is the preferred choice when the variable might change depending on the environment.

Constants

You can define a constant if the variable should be accessible in many different places and contexts. For example, you might want to create the file

config/initializers/defaults.rb

and write there all your default configurations and constants. A constant defined here will be automatically available all over your Rails application.

Helpers

If your variable is tied to a specific section of the application, for instance a view, you might want to take advantage of Rails helpers. In your specific case, you can create an image helper in your application_helper.rb

module ApplicationHelper

  THUMBNAIL_WIDTH = 50  

  def thumbnail_tag(source, options = {})
    image_tag(source, options.reverse_merge(:width => THUMBNAIL_WIDTH))
  end

end

Then use the helper when you need to create a thumbnail instead of copying the same logic over and over in every file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top