method
enum
v4.2.1 -
Show latest stable
-
0 notes -
Class: Enum
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (0)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
enum(definitions)
public
Hide source
# File activerecord/lib/active_record/enum.rb, line 82 def enum(definitions) klass = self definitions.each do |name, values| # statuses = { } enum_values = ActiveSupport::HashWithIndifferentAccess.new name = name.to_sym # def self.statuses statuses end detect_enum_conflict!(name, name.to_s.pluralize, true) klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values } _enum_methods_module.module_eval do # def status=(value) self[:status] = statuses[value] end klass.send(:detect_enum_conflict!, name, "#{name}=") define_method("#{name}=") { |value| if enum_values.has_key?(value) || value.blank? self[name] = enum_values[value] elsif enum_values.has_value?(value) # Assigning a value directly is not a end-user feature, hence it's not documented. # This is used internally to make building objects from the generated scopes work # as expected, i.e. +Conversation.archived.build.archived?+ should be true. self[name] = value else raise ArgumentError, "'#{value}' is not a valid #{name}" end } # def status() statuses.key self[:status] end klass.send(:detect_enum_conflict!, name, name) define_method(name) { enum_values.key self[name] } # def status_before_type_cast() statuses.key self[:status] end klass.send(:detect_enum_conflict!, name, "#{name}_before_type_cast") define_method("#{name}_before_type_cast") { enum_values.key self[name] } pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index pairs.each do |value, i| enum_values[value] = i # def active?() status == 0 end klass.send(:detect_enum_conflict!, name, "#{value}?") define_method("#{value}?") { self[name] == i } # def active!() update! status: :active end klass.send(:detect_enum_conflict!, name, "#{value}!") define_method("#{value}!") { update! name => value } # scope :active, -> { where status: 0 } klass.send(:detect_enum_conflict!, name, value, true) klass.scope value, -> { klass.where name => i } end end defined_enums[name.to_s] = enum_values end end