Browse the Ruby on Rails Community.

You are here: Forums Ask a Rails expert Static Objects in Rails...

Replytotopic

Static Objects in Rails

Posted in Forums : Ask a Rails expert

 
Profile

Authority 0
Posting Rating 0
Sign in to rate this post

Hi,

I want to create some static objects in rails that get created on startup. What is the best way to do this and where is best to put them for visibility from views (and possible controllers)?

Tks,
Michael

 
Profile

Authority 12
Posting Rating 96
Sign in to rate this post

You can define them as constants and place them in your environment.rb file

Example

SITE_TITLE = ‘Welcome to my website’

 
Me

Authority 37
Posting Rating 100
Sign in to rate this post

If you need them to be visible in views and controllers only (i.e. not in models), you could always define instance variables in your ApplicationController and load them with a before_filter. Imagine a shop site where you always need to display some kind of product list:

class ApplicationController < ActionController::Base
  before_filter :load_products

  # ... other code

  private
  def load_products
    @products = Product.find(:all)
  end
end

That’s what probably most developers would consider the Rails way …

HTH

 
Profile

Authority 0
Posting Rating 0
Sign in to rate this post

Hi Clemens,

Won’t load_products get called every time a controller method gets called? Sound like alot of overhead. Imagine the case where what you are loading are almost never going to change.

 
J2007_296_426_bw

Authority 62
Posting Rating 0
Sign in to rate this post

Hi,

I like to create a module in my lib folder with all these values. I also prefer to have them defined as class/module variables rather than as constants. That way, if I need to override a value (for example, in a initializer file) I will not get a warning.

You could put a file named my_config.rb in your lib folder with the following content

module MyConfig
mattr_accessor :my_variable
my_variable=’whatever’
end

Then from any place in your code (model, view, controller, helper, lib method, whatever) you can do something like
MyConfig.my_variable

If you prefer to use constants, you can do something like

module MyConfig
MY_CONSTANT=’whatever’
end

and then use it like

MyConfig::MY_CONSTANT

Regards,
javier

 
Avatar

Authority 37
Posting Rating 91
Sign in to rate this post

You may want to check out the plugin code here:

http://github.com/ctran/application_config/tree/master
 
Me

Authority 37
Posting Rating 100
Sign in to rate this post

Michael:
You’re definitely right – it depends on the kind of data you’re dealing with, I was just giving an example.

The plugin that Cuong mentioned is quite nifty. Other than that, Ryan Bates shows a great example in his Railscasts’ episode #85 (http://railscasts.com/episodes/85) where he uses YAML to store the config. You might want to take a look at this option.

 
Profile

Authority 12
Posting Rating 97
Sign in to rate this post

There is a really useful bit of code in section 61 of the Advanced Rails Recipes book. It’s called ConstantCache. I use a modified version of the code from the book in my app, but you can get it as a plugin now:

http://github.com/vigetlabs/constant_cache

In my app I have a few different Role objects, with title “Admin”, “User” etc. With this plugin I can modify my model by adding a “caches_constants” line like this:

class Role < ActiveRecord::Base
  caches_constants :key => :title
end

now when my rails app loads up, all of the different roles are loaded, and constants are added to the Role class. So in my authentication code I can refer to Role::ADMIN or Role::USER.

The instances of Role which are associated with each constant are only loaded once, when the application starts up.

 
Profile

Authority 12
Posting Rating 0
Sign in to rate this post

Javier:

I gave your method a shot and it looks like for the non-constant variables to work you have to declare them as instance variables:

module MyConfig
mattr_accessor :my_variable
@@my_variable=’whatever’
end

 
Bphogan

Authority 75
Posting Rating 33
Sign in to rate this post

The way that works well for my projects is to have a config.yml file in the config/ folder. In environment.rb, I just load that into a constant.

I might have this in the config file:


development:
    email:
      server: smtp.myserver.com
      port: 25
      domain: myserver.com
      authentication: none
      username: 
      password: 
      contact_recipient: <a href="mailto:admin@myserver.com">admin@myserver.com</a>
      content_type: text/html
  test_mode:true
  send_emails: false
  google_maps_api_key: 
production:
    email:
      server: smtp.myserver.com
      port: 25
      domain: myserver.com
      authentication: none
      username: 
      password: 
      contact_recipient: <a href="mailto:admin@myserver.com">admin@myserver.com</a>
      content_type: text/html
  test_mode:true
  send_emails: false
  google_maps_api_key: 

Then all I have to do is load that YAML to a constant in environment.rb.

CONFIGURLATION = YAML::load(File.open("#{RAILS_ROOT}/config/config.yml"))

In code, you can use CONFIGURATION[RAILS_ENV] to grab the values. Getting nested values is easy as it’s just a nested hash like params[].

For example

ActionMailer::Base.smtp_settings = {
 :address => CONFIGURATIONRAILS_ENV['server'],
 :port => CONFIGURATIONRAILS_ENV['port'],
 :domain => CONFIGURATIONRAILS_ENV['domain'],
 :authentication => CONFIGURATIONRAILS_ENV['authentication'],
 :user_name => CONFIGURATIONRAILS_ENV['username'],
 :password => CONFIGURATIONRAILS_ENV['password']
}

Hope this helps. It’s simple and extremely flexible.

If you want a database solution, I have a gem that generates a controller and model for simple situations. (a single table, one row, one column for each configuration). It also auto-generates the admin form to manage the table. More info at http://www.napcsweb.com/blog/category/products/

 
J2007_296_426_bw

Authority 62
Posting Rating 0
Sign in to rate this post

Hi Jerod,

I forgot a detail in my code when I pasted ;) you don’t need to use the @@ syntax, that’s why I used an mattr_accessor instead. You can do

module MyConfig mattr_accessor :my_variable MyConfig.my_variable=’whatever’
end

You can also use “self” instead of “MyConfig” but to me it looks clearer like that

Replytotopic

Other Recent Topics

Ask a Rails expert : how to write in model

Ask a Rails expert : how to show the params value in page.alert

Ask a Rails expert : Cutomize Will_Paginate next & previouse links

Ask a Rails expert : support AJAX pagination with Will_Paginate plug-in

Ask a Rails expert : Inheritance Determination in View

Ask a Rails expert : Install rails application

Ask a Rails expert : custom sql query

Ask a Rails expert : session handling does not work with REST API

Ask a Rails expert : Display WSDL

Ask a Rails expert : Howto respond a XML error message when there is no @active_record_obj?

Formatting Help
  • *bold*       _italics_      
    bq. (quotes)
  • "DSC":http://www.dsc.net
  • * or # (lists)
or cancel