Class: Phlexi::Form::SimpleChoicesMapper
- Inherits:
-
Object
- Object
- Phlexi::Form::SimpleChoicesMapper
- 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.
Instance Method Summary collapse
-
#[](value) ⇒ String?
Retrieves the label for a given value.
-
#each {|value, label| ... } ⇒ Enumerator
Iterates over the choices, yielding value-label pairs.
-
#initialize(collection, label_method: nil, value_method: nil) ⇒ SimpleChoicesMapper
constructor
Initializes a new SimpleChoicesMapper instance.
-
#labels ⇒ Array<String>
An array of all choice labels.
-
#values ⇒ Array<String>
An array of all choice values.
Constructor Details
#initialize(collection, label_method: nil, value_method: nil) ⇒ SimpleChoicesMapper
Initializes a new SimpleChoicesMapper instance.
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.
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.
45 46 47 |
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 45 def each(&) choices.each(&) end |
#labels ⇒ Array<String>
Returns An array of all choice labels.
50 51 52 |
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 50 def labels choices.values end |
#values ⇒ Array<String>
Returns An array of all choice values.
55 56 57 |
# File 'lib/phlexi/form/simple_choices_mapper.rb', line 55 def values choices.keys end |