Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If your model is really "responsible" for the constants you should stick them there. You can create class methods to access them without creating a new object instance:</p> <pre><code>class Card &lt; ActiveRecord::Base def self.colours ['white', 'blue'] end end # accessible like this Card.colours </code></pre> <p>Alternatively, you can create class variables and an accessor. This is however discouraged as class variables might act kind of surprising with inheritance and in multi-thread environments.</p> <pre><code>class Card &lt; ActiveRecord::Base @@colours = ['white', 'blue'] cattr_reader :colours end # accessible the same as above </code></pre> <p>The two options above allow you to change the returned array on each invocation of the accessor method if required. If you have true a truly unchangeable constant, you can also define it on the model class:</p> <pre><code>class Card &lt; ActiveRecord::Base COLOURS = ['white', 'blue'].freeze end # accessible as Card::COLOURS </code></pre> <p>You could also create global constants which are accessible from everywhere in an initializer like in the following example. This is probably the best place, if your colours are really global and used in more than one model context.</p> <pre><code># put this into config/initializers/my_constants.rb COLOURS = ['white', 'blue'].freeze </code></pre> <p><em>Note: when we define constants above, often we want to <code>freeze</code> the array. That prevents other code from later (inadvertently) modifying the array by e.g. adding a new element. Once an object is frozen, it can't be changed anymore.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload