Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I store constant data and then how to reference it in Rails?

I have a array of data, for example times (7:00am, 7:30am, etc.), that I want stored and referenced in a couple places.

1) Where should I store this data? I was originally thinking in my DB (I'm using mongoid) but I'm not sure if that's over kill.

2) How would I go about referencing it? Let's say, from a drop down menu.

like image 336
say Avatar asked Sep 08 '12 12:09

say


4 Answers

In this kind of situation, I create a Constants module in lib:

module Constants
  SCHEDULER_STEPS = %w( 7:00am 7:30am )
end

Then I access it wherever I need with:

Constants::SCHEDULER_STEPS

Note: be sure to add libs to your autoload path in the configuration file.

like image 64
apneadiving Avatar answered Nov 15 '22 12:11

apneadiving


I prefer to put this sort of data on the model it's most closely related to. For example, if the times in your example were the times to run a backup, put them in the Backup model with the rest of the behavior related to backups:

# app/models/backup.rb
class Backup < ActiveRecord::Base
  AVAILABLE_RUN_TIMES = %w{7:00am 7:30am ...}

  def run_at=(date)
    BackupSchedule.create(self, date)
  end
end

# app/views/backups/_form.html.erb
<%= select_tag(:run_at, options_for_select(Backup::AVAILABLE_RUN_TIMES)) %>

I've used the "big bucket of constants" approach too, but I would only use it if there's truly no more relevant place for the constants to live.

like image 30
Brandan Avatar answered Nov 15 '22 12:11

Brandan


For such kind of requirements i prefer

1st) create a config/app_constants.yml

Code here

production:
  time_list: "'7:00am','7:30am','7:40am'"
test:
  time_list: "'7:00am','7:30am','7:40am'"
development:
  time_list: "'7:00am','7:30am','7:40am'"

2nd Create under lib/app_constant.rb

module AppConstant
  extend self

  CONFIG_FILE = File.expand_path('../config/app_constants.yml', __FILE__)
  @@app_constants = YAML.load(File.read(CONFIG_FILE))
  @@constants = @@app_constants[Rails.env]

  def get_time_list
    @@constants['time_list'].split(',')
  end
end

3rd Call it anywhere like

AppConstant.get_time_list #will return an array

With this you just have to make changes at a single clean place(app_constants.yml) and will reflect throughout you application wherever AppConstant.get_time_list is used

like image 44
AnkitG Avatar answered Nov 15 '22 13:11

AnkitG


I ended up creating a "global_constants.rb" file in "/config/initializers" with the following code:

module Constants
    BUSINESS_HOURS = ["6:00am","6:15am","6:30am","6:45am","7:00am"]
end

Then I called the data with Constants::BUSINESS_HOURS, specifically for the select box, the code was: <%= f.input :hrs_op_sun_open, :collection => Constants::BUSINESS_HOURS %>

Many of the answers here seem viable and I suspect they are all correct ways of doing what I needed.

like image 23
say Avatar answered Nov 15 '22 13:11

say