views:

945

answers:

3

I'm creating two related Rails applications, and I'm noticing a lot of non-DRY work.

For example, the @title field being set in the various controller methods do the same thing, except for the application title, as in:

# SiteController (application 'Abc')
def SiteController < ApplicationController
  def index
    @title = 'Abc'
  end
  def about
    @title = 'about Abc'
  end
  def news
    @title = 'Abc news'
  end
  def contact
    @title = 'contact Abc'
  end
end

and:

# SiteController (application 'Xyz')
def SiteController < ApplicationController
  def index
    @title = 'Xyz'
  end
  def about
    @title = 'about Xyz'
  end
  def news
    @title = 'Xyz news'
  end
  def contact
    @title = 'contact Xyz'
  end
end

What I'm looking to do is have something like

# SiteController
def SiteController < ApplicationController
  def index
    @title = "#{ApplicationTitle}'
  end
  def about
    @title = "about #{ApplicationTitle}"
  end
  def news
    @title = "#{ApplicationTitle} news"
  end
  def contact
    @title = "contact #{ApplicationTitle}"
  end
end

The thing I'm trying to figure is: where should non-changing application settings be defined. Is it in a config/*rb file? Is it in one of the .yaml files?

Thanks in advance

+2  A: 

Hi, you can put them in the app/controllers/application.rb file.

For example:

class ApplicationController < ActionController::Base
  attr_accessor :application_title

  def initialize
    self.application_title = "Some application title"
  end
end

Then in your controllers, you can access the title as:

class SomeController < ApplicationController
  def some_action
    @title = "some text with #{application_title}"
  end
end

You can also declare the application title as a helper method so it can be accessed in your views.

You can also use global constants, and put it in your config/environment.rb file. Put it at the most bottom part of the environment.rb, outside the configuration block, like this:

APPLICATION_TITLE = "Some title here"

Then use the constant whenever you set the @title instance variable in your controller. Note, it has to be all caps, so Ruby will interpret it as a global constant.

markjeee
Thanks. I knew about the ApplicationController one, but wasn't sure about the environment.rb
dcw
+4  A: 

For something as basic as the apps name, plus a lot of other constants, I declare the constants in environment.rb

Constants should use the Ruby constants feature, not a class variable with an accessor as markjeee suggested.

Ref: pg 330, "Programming Ruby" (Pickaxe) 2nd Ed.

Larry

Larry K
Thanks. I am intending it to be a constant, but wasn't sure about environment.rb (or anywhere else, for that matter).
dcw
+1  A: 

Define the constants in the config/environment.rb file

DannyT