Class: Superform::Rails::OptionMapper

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/superform/rails/option_mapper.rb

Overview

Accept a collection of objects and map them to options suitable for form controls, like ‘select > options`

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ OptionMapper

Returns a new instance of OptionMapper.



7
8
9
# File 'lib/superform/rails/option_mapper.rb', line 7

def initialize(collection)
  @collection = collection
end

Instance Method Details

#active_record_relation_options_enumerable(relation) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/superform/rails/option_mapper.rb', line 24

def active_record_relation_options_enumerable(relation)
  Enumerator.new do |collection|
    relation.each do |object|
      attributes = object.attributes
      id = attributes.delete(relation.primary_key)
      value = attributes.values.join(" ")
      collection << [ id, value ]
    end
  end
end

#each(&options) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/superform/rails/option_mapper.rb', line 11

def each(&options)
  @collection.each do |object|
    case object
      in ActiveRecord::Relation => relation
        active_record_relation_options_enumerable(relation).each(&options)
      in id, value
        options.call id, value
      in value
        options.call value, value.to_s
    end
  end
end