Sha256: 3b8c56a5bda7d4c9906c3e0b879cb172fd206a7f88b6b5888ba5150cd4541635

Contents?: true

Size: 865 Bytes

Versions: 1

Compression:

Stored size: 865 Bytes

Contents

module JT
	module Rails
		module Enum
			extend ActiveSupport::Concern

			class_methods do

				def jt_enum(definitions)
					klass = self

					definitions.each do |field, values|

						enum_values = ActiveSupport::HashWithIndifferentAccess.new

						klass.singleton_class.send(:define_method, field.to_s.pluralize) { enum_values }

						values.each_with_index do |value, i|
							value_method_name = "#{field}_#{value}"

							enum_values[value] = i

							define_method("#{value_method_name}?") { self[field] == i }
							define_method("#{value_method_name}!") { update! field => i }

							klass.scope value_method_name, -> { klass.where field => i }
						end

						validates field, allow_nil: true, inclusion: { in: klass.send(field.to_s.pluralize).values } 

					end
				end
			end
		end
	end
end

ActiveRecord::Base.send :include, JT::Rails::Enum

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jt-rails-enum-1.0.1 lib/jt-rails-enum.rb