Refactoring Ruby on Rails

Ruby on Rails / Refactoring – speed up your app with frozen constants

Ruby on Rails / Refactoring – speed up your app with frozen constants January 27, 20183 Comments

Let’s consider the very simple ruby method which takes a country code and returns a country name. I’m sure that many of us write similar methods, especially at the beginning of the Ruby journey.

class SampleClass
  def country_name(country_code:)
    mappings = {
      'us' => 'USA',
      'de' => 'Germany'
    }
    
    mappings[country_code]
  end
end

To make things more readable we can move mappings outside the method. Moving them to the separated method is ok. Moving them to the constant is good. But moving them to the frozen constant is perfect because it saves some memory for us:

class SampleClass
  COUNTRY_CODES_MAPPINGS = {
    'us' => 'USA',
    'de' => 'Germany'
  }.freeze
  
  def country_name(country_code:)
    COUNTRY_CODES_MAPPINGS[country_code]
  end
end

Without freezing our constant you will be able to change its value but with a frozen constant you can’t do it – you will experience RuntimeError. Generally, freezing also saves memory for us because it reduces memory allocation.

What’s interesting with Ruby 2.2 string literals used in hash keys are automatically frozen.

Special thanks to my workmate, Darek, who showed me this trick.

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

3 comments

  1. Notice that you can still change the hash values since they aren’t frozen.

    “`
    COUNTRY_CODES_MAPPINGS.values.map(&:frozen?)
    # [false, false]
    “`

    You can change them like this:

    “`
    COUNTRY_CODES_MAPPINGS[‘us’].replace(“a”)
    “`

Leave a Reply

Your email address will not be published. Required fields are marked *