Ruby on Rails: Where to define global constants?

前端 未结 12 1780
我在风中等你
我在风中等你 2020-11-28 00:44

I\'m just getting started with my first Ruby on Rails webapp. I\'ve got a bunch of different models, views, controllers, and so on.

I\'m wanting to find a good plac

12条回答
  •  半阙折子戏
    2020-11-28 01:13

    I typically have a 'lookup' model/table in my rails program and use it for the constants. It is very useful if the constants are going to be different for different environments. In addition, if you have a plan to extend them, say you want to add 'yellow' on a later date, you could simply add a new row to the lookup table and be done with it.

    If you give the admin permissions to modify this table, they will not come to you for maintenance. :) DRY.

    Here is how my migration code looks like:

    class CreateLookups < ActiveRecord::Migration
      def change
        create_table :lookups do |t|
          t.string :group_key
          t.string :lookup_key
          t.string :lookup_value
          t.timestamps
        end
      end
    end
    

    I use seeds.rb to pre-populate it.

    Lookup.find_or_create_by_group_key_and_lookup_key_and_lookup_value!(group_key: 'development_COLORS', lookup_key: 'color1', lookup_value: 'red');
    

提交回复
热议问题