Last active
June 14, 2019 14:41
-
-
Save odlp/0787f854f58160dcaaa40aba36629007 to your computer and use it in GitHub Desktop.
Rails shorthand string enum values
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
# frozen_string_literal: true | |
# app/models/concerns | |
module HasStringEnum | |
extend ActiveSupport::Concern | |
class_methods do | |
def string_enum(name, values, **options) | |
enum(name => values.zip(values).to_h, **options) | |
end | |
end | |
end |
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
# frozen_string_literal: true | |
class MyModel < ApplicationRecord | |
include HasStringEnum | |
string_enum :rate_type, %w(hourly regular) | |
# Instead of repeating the values twice: | |
# enum default_rate_type: { hourly: "hourly", weekly: "weekly" } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment