Custom Rails Symbol Serializer

July 25, 2019

Rails comes with some built in model serializers such as Array and JSON which transform data from the database into your preferred format. In some cases, you may have a string column that you'd rather interact with via symbols.

Find or create a lib/serializers directory, then create symbol_serializer.rb and add the following:

class SymbolSerializer
  def self.dump(sym)
    sym ? sym.to_s : nil

  def self.load(text)
    text ? text.to_sym : nil

Before we can use this new serializer, we need to add the lib/serializers path to our autoload config in config/application.rb.

config.autoload_paths += %W(
  # ...
  # ...

Now it can be used on any ActiveRecord model.

class Person < ApplicationRecord
  serialize :status, SymbolSerializer

user = Person.create(status: :active)
#=> :active

user.update(status: 'blocked')
#=> :blocked

Notice you can still pass strings to your model and it will convert back to a symbol once you save and call the method's getter again.