Created
May 17, 2019 14:58
-
-
Save Loschcode/b74ecd49272112baa5384aa00e84c6a7 to your computer and use it in GitHub Desktop.
This file contains 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
# MIGRATION | |
change_column :my_table, :status, :string | |
# LOGICS | |
module SafeEnumHelper | |
def self.ensure(resource:, column:, mapping:) | |
raw_status = resource.attributes_before_type_cast[column] | |
is_integer = /\A[-+]?\d+\z/ === raw_status | |
if is_integer | |
mapping[raw_status.to_sym] if is_integer | |
else | |
raw_status | |
end | |
end | |
end | |
# USE IN MODEL | |
def status | |
SafeEnumHelper.ensure( | |
resource: self, | |
column: 'status', | |
mapping: { | |
'0': 'draft', | |
'1': 'publish', | |
'2': 'trash' | |
} | |
) | |
end | |
enum status: { draft: 'draft', publish: 'publish', trash: 'trash' } | |
# enum status: [:draft, :publish, :trash] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment