Last active
July 9, 2019 03:01
-
-
Save jcypret/3b083fc1292d7f24cd26fa24af7788d2 to your computer and use it in GitHub Desktop.
Store ActiveRecord enums in database as strings rather than integers
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
# Store enums in database as strings rather than integers. | |
# | |
# Wraps `ActiveRecord::Enum`; just use `string_enum` instead of `enum`. | |
# https://api.rubyonrails.org/v4.2.11.1/classes/ActiveRecord/Enum.html | |
# | |
# Usage: | |
# extend StringEnum | |
# string_enum status: [:active, :archived] | |
# | |
module StringEnum | |
def string_enum(definitions) | |
definitions.each do |name, values| | |
enum name => values.each_with_object({}) { |value, enums| enums[value] = value.to_s } | |
# override attribute getter to return a symbol | |
define_method(name) { self[name]&.to_sym } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment