Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 995
ipso facto Avatar asked Jul 08 '09 15:07

ipso facto


People also ask

What is an ERB template?

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.

What are partials in Rails?

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.

What is view in Ruby?

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.


1 Answers

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.

like image 146
Simone Carletti Avatar answered Nov 15 '22 16:11

Simone Carletti