Ruby on Rails: Where to define global constants?

前端 未结 12 1752
我在风中等你
我在风中等你 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:12

    Some options:

    Using a constant:

    class Card
      COLOURS = ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
    end
    

    Lazy loaded using class instance variable:

    class Card
      def self.colours
        @colours ||= ['white', 'blue', 'black', 'red', 'green', 'yellow'].freeze
      end
    end
    

    If it is a truly global constant (avoid global constants of this nature, though), you could also consider putting a top-level constant in config/initializers/my_constants.rb for example.

提交回复
热议问题