Skip to content

Instantly share code, notes, and snippets.

@odlp
Last active June 14, 2019 14:41
Show Gist options
  • Save odlp/0787f854f58160dcaaa40aba36629007 to your computer and use it in GitHub Desktop.
Save odlp/0787f854f58160dcaaa40aba36629007 to your computer and use it in GitHub Desktop.
Rails shorthand string enum values
# 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
# 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