Question

I've been programming in Ruby for a few months now, and I'm wondering when it is appropriate to use constants over class variables and vice versa. (I'm working in Rails, thinking about constants in models).

class Category
  TYPES = %w(listing event business).freeze
end

OR

class Category
  @@types = %w(listing event business).freeze
  cattr_reader :types
end

Are there circumstances where one is preferable to another? Or is it just a matter of taste/style?

Was it helpful?

Solution

The main thing is that by using the CONSTANT notation, you're making it clear to the reader. the lower case, frozen string gives the impression is might be settable, forcing someone to go back and read the RDoc.

OTHER TIPS

If these are really constant values that you define in source code and do not want to change during code execution then I would recommend to use constant.

If you plan to set and/or change these values dynamically during execution then use class variable with getters and setters.

Basically, you could put it like this: If you want something that's constant, use a constant. If you want something that's variable, use a variable. It seems like your list of types are constants, seeing it is a frozen array, so I would say it makes sense to use a constant in this case.

If you don't want the value to ever change during the runtime of your program, and you are comfortable with allowing the value to be accessed outside of your class, use a constant.

Otherwise, you can use a class variable. However, be aware that class variables are shared among subclasses and instances of subclasses. So if you might at some point in the future implement a child class, you have to be very careful about your use of class variables.

Refer to the answers here for more on this: Class variables in Ruby

If you want to make your Constant private you can always do:

FOO = 18
private_constant :FOO
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top