Sha256: d8fce1975485c147bc8979d68e304b67937f6ec0e9043ebea4c48d3e4e24c0e6
Contents?: true
Size: 1.12 KB
Versions: 1
Compression:
Stored size: 1.12 KB
Contents
require "active_support/concern" module StrEnum module Model extend ActiveSupport::Concern class_methods do def str_enum(column, values, validate: true, scopes: true, accessor_methods: true, prefix: false, suffix: false, default: true) values = values.map(&:to_s) validates column, presence: true, inclusion: {in: values} if validate values.each do |value| prefix = column if prefix == true suffix = column if suffix == true method_name = [prefix, value, suffix].select { |v| v }.join("_") scope method_name, -> { where(column => value) } if scopes && !respond_to?(method_name) if accessor_methods && !method_defined?("#{method_name}?") define_method "#{method_name}?" do read_attribute(column) == value end end end default_value = default == true ? values.first : default after_initialize do send("#{column}=", default_value) unless try(column) end define_singleton_method column.to_s.pluralize do values end end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
str_enum-0.1.5 | lib/str_enum/model.rb |