Class: TypesafeEnum::Base

Inherits:
Object
  • Object
show all
Extended by:
ClassMethods
Includes:
Comparable
Defined in:
lib/typesafe_enum/base.rb

Overview

Base class for typesafe enum classes.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ClassMethods

each, each_key, each_value, find_by_key, find_by_ord, find_by_value, find_by_value!, find_by_value_str, find_by_value_str!, keys, size, to_a, values

Instance Attribute Details

#keySymbol (readonly)

The symbol key for the enum instance

Returns:

  • (Symbol)

    the key



20
21
22
# File 'lib/typesafe_enum/base.rb', line 20

def key
  @key
end

#ordInteger (readonly)

The ordinal of the enum instance, in declaration order

Returns:

  • (Integer)

    the ordinal



28
29
30
# File 'lib/typesafe_enum/base.rb', line 28

def ord
  @ord
end

#valueObject (readonly)

The value encapsulated by the enum instance

Returns:

  • (Object)

    the value



24
25
26
# File 'lib/typesafe_enum/base.rb', line 24

def value
  @value
end

Instance Method Details

#<=>(other) ⇒ Integer?

Compares two instances of the same enum class based on their declaration order

Parameters:

  • other (self)

    the enum instance to compare

Returns:

  • (Integer, nil)

    -1 if this value precedes other; 0 if the two are the same enum instance; 1 if this value follows other; nil if other is not an instance of this enum class



35
36
37
38
39
40
# File 'lib/typesafe_enum/base.rb', line 35

def <=>(other)
  # in the case where the enum being compared is actually the parent
  # class, only `==` will work correctly & we cannot use #is_a? or
  # #instance_of?
  ord <=> other.ord if self.class == other.class
end

#hashFixnum

Generates a Fixnum hash value for this enum instance

Returns:

  • (Fixnum)

    the hash value



44
45
46
47
48
49
50
51
# File 'lib/typesafe_enum/base.rb', line 44

def hash
  @hash ||= begin
    result = 17
    result = 31 * result + self.class.hash
    result = 31 * result + ord
    result.is_a?(Integer) ? result : result.hash
  end
end

#to_sString

Default implementation includes the enum class, key, ord and value.

Returns:

  • (String)

    a string representation of the enum instance



56
57
58
# File 'lib/typesafe_enum/base.rb', line 56

def to_s
  "#{self.class}::#{key} [#{ord}] -> #{value.inspect}"
end