Ruby on Rails: Where to define global constants ?

Ruby on Rails: Where to define global constants ?

Asked on December 28, 2018 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    The “responsible”  constants  create a class methods to access to without creating a new object instance,

    class Card < ActiveRecord::Base
       def self.colours
          ['white', 'blue']
       end
    end
     
    # accessible like this
    Card.colours
    

    Create class variables  an accessor. A class variables might act  as inheritance and  multi-thread environments,

    class Card < ActiveRecord::Base
      @@colours = ['white', 'blue']
      cattr_reader :colours
    end
     
    # accessible the same as above
    

    Both options change and  the returned array on each invocation of the accessor method . The unchangeable constant  define as a model class:

    class Card < ActiveRecord::Base
      COLOURS = ['white', 'blue'].freeze
    end
     
    # accessible as
    Card::COLOURS
    

    The color are really global and used in more than one model context,

    # put this into config/initializers/my_constants.rb
    COLOURS = ['white', 'blue'].freeze
    

    Answered on December 28, 2018.
    Add Comment

    There are some methods on  global constants: 

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

    Loading a class variable: 

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

    Using top-level constant in config/initializers/my_constants.rb.

    Answered on December 28, 2018.
    Add Comment

    In Rails 5.0, configuration object directly for custom configuration

    config/application.rb or config/custom.rb 

    config.colours = %w(white blue black red green)
    

    And creating in: 

    Rails.configuration.colours # => ["white", "blue", "black", "red", "green"]
    

    using  config.x  method: 

    config.x.colours = %w(white blue black red green)
    

    And available as:

    Rails.configuration.x.colours # => ["white", "blue", "black", "red", "green"]
    

    Answered on December 28, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.