Class: Phlexi::Form::SimpleChoicesMapper

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/phlexi/form/simple_choices_mapper.rb

Overview

Note:

This class is thread-safe as it doesn’t maintain mutable state.

SimpleChoicesMapper is responsible for converting a collection of objects into a hash of options suitable for form controls, such as ‘select > options`. Both values and labels are converted to strings.

Examples:

Basic usage

collection = [["First", 1], ["Second", 2]]
mapper = SimpleChoicesMapper.new(collection)
mapper.each { |value, label| puts "#{value}: #{label}" }

Using with ActiveRecord objects

users = User.all
mapper = SimpleChoicesMapper.new(users)
mapper.each { |id, name| puts "#{id}: #{name}" }

Array access with different value types

mapper = SimpleChoicesMapper.new([["Integer", 1], ["String", "2"], ["Symbol", :three]])
puts mapper["1"]      # Output: "Integer"
puts mapper["2"]      # Output: "String"
puts mapper["three"]  # Output: "Symbol"

Instance Method Summary collapse

Constructor Details

#initialize(collection, label_method: nil, value_method: nil) ⇒ SimpleChoicesMapper

Initializes a new SimpleChoicesMapper instance.

Parameters:

  • collection (#call, #to_a)

    The collection to be mapped.

  • label_method (Symbol, nil) (defaults to: nil)

    The method to call on each object to get the label.

  • value_method (Symbol, nil) (defaults to: nil)

    The method to call on each object to get the value.



34
35
36
37
38
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 34

def initialize(collection, label_method: nil, value_method: nil)
  @collection = collection
  @label_method = label_method
  @value_method = value_method
end

Instance Method Details

#[](value) ⇒ String?

Retrieves the label for a given value.

Parameters:

  • value (#to_s)

    The value to look up.

Returns:

  • (String, nil)

    The label corresponding to the value, or nil if not found.



63
64
65
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 63

def [](value)
  choices[value.to_s]
end

#each {|value, label| ... } ⇒ Enumerator

Iterates over the choices, yielding value-label pairs.

Yield Parameters:

  • value (String)

    The string value for the current choice.

  • label (String)

    The string label for the current choice.

Returns:

  • (Enumerator)

    If no block is given.



45
46
47
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 45

def each(&)
  choices.each(&)
end

#labelsArray<String>

Returns An array of all choice labels.

Returns:

  • (Array<String>)

    An array of all choice labels.



50
51
52
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 50

def labels
  choices.values
end

#valuesArray<String>

Returns An array of all choice values.

Returns:

  • (Array<String>)

    An array of all choice values.



55
56
57
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 55

def values
  choices.keys
end