Search code examples
ruby-on-railsruby

Should I use freeze for ActiveSupport::Duration objects?


When I define some constants with duration

EXAMPLE_DAYS = 12.days

it will not be frozen

> EXAMPLE_DAYS.frozen?
false

And in ruboсop there are no corresponding rules.

Is it necessary to freeze constants with such objects at all?


Solution

  • It depends on the type of object you assign to the constant. For an instance of ActiveSupport::Duration it doesn't really make sense to freeze it, because it doesn't have any public writer method that allows changing it. But you still can, when you want to please Rubocop.

    DAYS = 12.days.freeze
    DAYS.frozen?
    #=> true
    

    For other object like, for example, a string it absolutely makes sense to freeze them, because they can change when it is not frozen and you usually want constants not to change.

    STRING = 'string'
    STRING[1..4] = '----'
    STRING
    #=> "s----g"
    

    But when frozen:

    STRING = 'string'.freeze
    STRING[1..4] = '----'
    #=> `[]=': can't modify frozen String: "string" (FrozenError)