Better approach to set global values?

Hi everyone,

I would like to set some site-wide (global) values across my application layout. All these global values are stored in my Settings table.

So in my Application controller I have something like this:

#Application Controller:

before_filter :grab_settings

def grab_settings    @set = Setting.first end

#Application Layout view

<div>   <p><%= @set.company_name %></p> </div>

All of this works fine, though. But if the "company_name" field is empty, than you wouldn't see anything. So in that case I would like to default to a other value.

I fixed that by doing the following:

<div>

  <% if @set.company_name.empty? %>      <p>My company</p>    <% else %>      <p><%= @set.company_name %></p>   <% end %>

</div>

However isn't there a better way to do this? Initially I thought I could do something more elegant like this:

<%= @set.company_name || "My company" %> but ofcourse, that won't work.

So basically I'm looking for a more polished/clean/better approach.

Any help is appreciated.

Thanks in advance!

John N. wrote in post #963524:

def grab_settings    @set = Setting.first

     @set.company_name ||= 'My Company'

end

Well, you could always read the Settings, then impose your own defaults inside the grab_settings method. Any code outside that method has no idea whether the value was read, or set by you. It just knows that the value is filled.

However isn't there a better way to do this? Initially I thought I could do something more elegant like this:

How about moving the config out of the code by using the plugin.

You can put your defaults in a file default.yml and then "over-ride" with them with a separate production.yml etc etc.

Another alternative is to just use the existing rails environment config or initializers file(s) to store such info in memory, something like:

$ cat ./config/environment.rb ... APP_VALS = {   :default_company_name = 'My Company', } ...

$ ./script/console ...

APP_VALS[:default_company_name]

=> "My Company"

If you wanted different vals per environment (ie test, development, production), then you could define APP_VALS in each of those environment config files.

Jeff

However isn't there a better way to do this? Initially I thought I could do something more elegant like this:

How about moving the config out of the code by using the plugin.GitHub - cjbottaro/app_config: Rails plugin that provides environment specific application configuration.

You can put your defaults in a file default.yml and then "over-ride" with them with a separate production.yml etc etc.

If you wanted different vals per environment (ie test, development, production), then you could define APP_VALS in each of those environment config files.

Or save some time and use SettingsLogic...