Skip to content

Instantly share code, notes, and snippets.

@ajlai
Last active December 11, 2015 16:48
Show Gist options
  • Save ajlai/4630236 to your computer and use it in GitHub Desktop.
Save ajlai/4630236 to your computer and use it in GitHub Desktop.
# Facilitate manipulating symbols as AR attribute values while storing them as other values in the DB
#
# Examples
#
# class Example < ActiveRecord::Base
# serialize :type, SymbolMapper.for(foo: 1, bar: 2, baz: 3)
# end
#
# example.type = :foo
# # => :foo
# example.read_attribute_before_type_cast(:type)
# # => 3
# example.reload.type
# # => :foo
class SymbolMapper
def self.for(mapping)
new(mapping)
end
def initialize(mapping)
@mapping = mapping
end
def load(val)
@mapping.key(val)
end
def dump(sym)
@mapping[sym]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment