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?
An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.
A partial allows you to separate layout code out into a file which will be reused throughout the layout and/or multiple other layouts. For example, you might have a login form that you want to display on 10 different pages on your site.
Advertisements. A Rails View is an ERb program that shares data with controllers through mutually accessible variables. If you look in the app/views directory of the library application, you will see one subdirectory for each of the controllers, we have created: book.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With