Last active
December 11, 2015 16:48
-
-
Save ajlai/4630236 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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