Class: ClassyEnum::Base

Inherits:
Object
  • Object
show all
Includes:
Collection, Conversion, Predicate, Translation, Comparable
Defined in:
lib/classy_enum/base.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Collection

#<=>, #enum_options, included

Methods included from Translation

#text

Methods included from Predicate

define_predicate_method

Methods included from Conversion

#as_json, #to_i, #to_s, #to_sym

Instance Attribute Details

#allow_blankObject

Returns the value of attribute allow_blank


11
12
13
# File 'lib/classy_enum/base.rb', line 11

def allow_blank
  @allow_blank
end

#ownerObject

Returns the value of attribute owner


11
12
13
# File 'lib/classy_enum/base.rb', line 11

def owner
  @owner
end

Class Method Details

.base_classObject


18
19
20
# File 'lib/classy_enum/base.rb', line 18

def base_class
  @base_class ||= superclass.base_class
end

.base_class=(klass) ⇒ Object


22
23
24
# File 'lib/classy_enum/base.rb', line 22

def base_class=(klass)
  @base_class = klass
end

.build(value, options = {}) ⇒ Object

Used internally to build a new ClassyEnum child instance It is preferred that you use ChildClass.new instead

Example

# Create an Enum with some elements
class Priority < ClassyEnum::Base
end

class Priority::Low < Priority
end

Priority.build(:low) # => Priority::Low.new
Priority.build(:invalid_option) # => :invalid_option

60
61
62
63
64
65
66
67
68
69
# File 'lib/classy_enum/base.rb', line 60

def build(value, options={})
  object = find(value)

  if object.nil?
    value
  else
    object.owner = options[:owner]
    object
  end
end

.inherited(klass) ⇒ Object


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/classy_enum/base.rb', line 26

def inherited(klass)
  if self == ClassyEnum::Base
    klass.base_class = klass
  else

    # Ensure subclasses follow expected naming conventions
    unless klass.name.start_with? "#{base_class.name}::"
      raise SubclassNameError, "subclass must be namespaced with #{base_class.name}::"
    end

    # Convert from MyEnumClass::NumberTwo to :number_two
    enum = klass.name.split('::').last.underscore.to_sym

    Predicate.define_predicate_method(klass, enum)

    klass.instance_variable_set('@option', enum)
  end

  super
end

.owner(owner) ⇒ Object

DSL setter method for overriding reference to enum owner (ActiveRecord model)

Example

# Create an Enum with some elements
class Priority < ClassyEnum::Base
  owner :alarm
end

class Priority::High < Priority
  def send_alarm?
    alarm.enabled?
  end
end

84
85
86
# File 'lib/classy_enum/base.rb', line 84

def owner(owner)
  define_method owner, -> { @owner }
end

Instance Method Details

#base_classObject


13
14
15
# File 'lib/classy_enum/base.rb', line 13

def base_class
  self.class.base_class
end