Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Loschcode/b74ecd49272112baa5384aa00e84c6a7 to your computer and use it in GitHub Desktop.
Save Loschcode/b74ecd49272112baa5384aa00e84c6a7 to your computer and use it in GitHub Desktop.
# 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