Class: Superform::Rails::Choices::Mapper

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

Overview

Maps collections of options into (value, text) pairs for form controls. Accepts arrays, hashes, single values, and ActiveRecord relations.

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ Mapper

Returns a new instance of Mapper.



9
10
11
# File 'lib/superform/rails/choices/mapper.rb', line 9

def initialize(collection)
  @collection = collection
end

Instance Method Details

#active_record_relation_options_enumerable(relation) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/superform/rails/choices/mapper.rb', line 28

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



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/superform/rails/choices/mapper.rb', line 13

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