james
james

Reputation: 4049

How to store constants (e.g., text string) for use in different View files

I have a block of disclaimer text used across multiple pages/ partials. I figure I could:

  1. make this block of text a partial itself and then call this partial whenever I need
  2. save this block of text as an environment variable
  3. save this block of text as a shared method with an instance variable, and then include that instance variable in all the methods corresponding with pages that need it like so:

Example of #3:

def disclaimer
    @text = "text"
end

def homepage
    disclaimer
end

def page_one
    disclaimer
end

# then the view file for homepage or page_one would just call  @text

Which of these ways is more "Rails"?

Upvotes: 0

Views: 523

Answers (2)

Cory Stephenson
Cory Stephenson

Reputation: 26

As stated in your question, there are a few ways to do this. Your best best is to either use a partial, or make a helper and define a method for your disclaimer in the helper.

Helpers should be a bit faster, because they aren't rendering the partial. This is the best bet if your disclaimer is static text. If you are using any HTML in your disclaimer, it would probably be better to use a partial.

Example helper:

module DisclaimerHelper
  def disclaimer
    "This is the static text of my disclaimer."
  end
end

Upvotes: 1

arjabbar
arjabbar

Reputation: 6404

I would definitely go with option 1. Environment variables are usually reserved for credentials to services that your app uses and option 3 seems like it would be a little more complex than option 1.

Upvotes: 0

Related Questions