Class: EnumTable::Reflection

Inherits:
Object
  • Object
show all
Defined in:
lib/enum_table/reflection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Reflection

Returns a new instance of Reflection.



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/enum_table/reflection.rb', line 3

def initialize(name, options={})
  @name = name
  @id_name = options[:id_name] || :"#{name}_id"
  @type = options[:type] || :symbol
  @type == :string || @type == :symbol or
    raise ArgumentError, "invalid type: #{type.inspect}"

  @strings_to_ids = {}
  @values_to_ids = {}
  @ids_to_values = {}
end

Instance Attribute Details

#id_nameObject

Returns the value of attribute id_name.



26
27
28
# File 'lib/enum_table/reflection.rb', line 26

def id_name
  @id_name
end

#nameObject (readonly)

Returns the value of attribute name.



25
26
27
# File 'lib/enum_table/reflection.rb', line 25

def name
  @name
end

#typeObject

Returns the value of attribute type.



26
27
28
# File 'lib/enum_table/reflection.rb', line 26

def type
  @type
end

Instance Method Details

#add_value(id, value) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/enum_table/reflection.rb', line 28

def add_value(id, value)
  @strings_to_ids[value.to_s] = id

  cast_value = @type == :string ? value.to_s : value.to_sym
  @values_to_ids[cast_value] = id
  @ids_to_values[id] = cast_value
end

#id(value) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/enum_table/reflection.rb', line 36

def id(value)
  if value.is_a?(String) || type == :string
    @strings_to_ids[value.to_s.strip]
  else
    @values_to_ids[value]
  end
end

#initialize_copy(other) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/enum_table/reflection.rb', line 15

def initialize_copy(other)
  @name = other.name
  @id_name = other.id_name
  @type = other.type

  @strings_to_ids = other.instance_variable_get(:@strings_to_ids).dup
  @values_to_ids = other.instance_variable_get(:@values_to_ids).dup
  @ids_to_values = other.instance_variable_get(:@ids_to_values).dup
end

#value(id) ⇒ Object



44
45
46
# File 'lib/enum_table/reflection.rb', line 44

def value(id)
  @ids_to_values[id]
end

#valuesObject



48
49
50
# File 'lib/enum_table/reflection.rb', line 48

def values
  @values_to_ids.keys
end