say
say

Reputation: 2655

Rails: How to store a value in one place and reference it in others

I would like to store a value, say the name of my app, in one place (like a constant) and then reference that throughout my app.Therefor if I need to make a global change I can make it in once place and it update throughout my app. Here is one idea on how I can make it work:

In a constants file
APPLICATION_NAME = "FuzzyOnions"

In any view I can now reference it like this:
You are going to love using the <%= Constants::APPLICATION_NAME %> application.

The problem I'm running into is when I try to reference it in places such as: <% @page_title = "<%= Constants::APPLICATION_NAME %> / About" %> rails throws an error. It also throws an error if I try to reference the constant in a link such as %= link_to 'Contact Us <%= Constants::APPLICATION_NAME %>', page_path("contact-us") %>

Is there another way to reference a constant that will not throw an error in these instances? Is there a better way to accomplish what I'm trying to do to begin with?

Upvotes: 1

Views: 89

Answers (2)

Michael Durrant
Michael Durrant

Reputation: 96484

<% @page_title = "<%= Constants<::APPLICATION_NAME %> / About" %> 

should be

<% @page_title = Constants::APPLICATION_NAME + " / About" %> 

And:

<%= link_to 'Contact Us <%= Constants::APPLICATION_NAME %>', page_path("contact-us") %>

should be

<%= link_to 'Contact Us '+ Constants::APPLICATION_NAME, page_path("contact-us") %>

Upvotes: 2

Steve Enzer
Steve Enzer

Reputation: 1

You have a module named YourAppName (whatever that is) in application.rb This could work:

module YourAppName
  class << self
      def [] s
      constants[s]
    end
    def constants
      # you could read this in as a yaml file, cache in a class var, etc.
      {application_name: 'Fuzzy Onions',
       url: 'fuzzy-onions.com'} 
    end




 YourAppName[:application_name]
 => "Fuzzy Onions"  

 AbServ[:url]
 => "fuzzy-onions.com" 

Upvotes: 0

Related Questions