Class: FlexibleEnum::PotentialValuesConfigurator

Inherits:
AbstractConfigurator show all
Defined in:
lib/flexible_enum/potential_values_configurator.rb

Defined Under Namespace

Classes: Option

Instance Attribute Summary

Attributes inherited from AbstractConfigurator

#attribute_name, #elements, #feature_module, #module_for_elements

Instance Method Summary collapse

Methods inherited from AbstractConfigurator

#add_class_method, #add_instance_method

Instance Method Details

#applyObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/flexible_enum/potential_values_configurator.rb', line 3

def apply
  configurator = self

  add_class_method(attribute_name.to_s.pluralize) do
    configurator.elements.map(&configurator.option_builder_for_target(self)).sort_by(&:value)
  end

  add_class_method("#{attribute_name.to_s.pluralize}_by_sym") do
    configurator.elements.inject({}) do |all_options, (element_name, element_config)|
      all_options.merge element_name => configurator.option_builder_for_target(self).call(element_name, element_config)
    end
  end

  add_class_method("#{attribute_name}_value_for") do |sym_string_or_const|
    element_by_symbol = send(:"#{configurator.attribute_name.to_s.pluralize}_by_sym")[:"#{sym_string_or_const.to_s.downcase}"]
    element_by_value = send(configurator.attribute_name.to_s.pluralize).select { |e| e.value == sym_string_or_const }.first
    (element_by_symbol || element_by_value).try(:value) or raise("Unknown enumeration element: #{sym_string_or_const}")
  end
end

#option_builder_for_target(target_instance) ⇒ Object



23
24
25
# File 'lib/flexible_enum/potential_values_configurator.rb', line 23

def option_builder_for_target(target_instance)
  proc { |element_name, element_config| Option.new(target_instance, attribute_name, element_name, element_config) }
end