Module: Flatter::Mapper::Collection

Included in:
Flatter::Mapper
Defined in:
lib/flatter/mapper/collection.rb

Defined Under Namespace

Modules: Concern, FactoryMethods

Constant Summary collapse

NonUniqKeysError =
Class.new(RuntimeError)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prepended(base) ⇒ Object



5
6
7
# File 'lib/flatter/mapper/collection.rb', line 5

def self.prepended(base)
  base.send(:include, Concern)
end

Instance Method Details

#collectionObject



161
162
163
164
165
166
167
168
169
170
171
# File 'lib/flatter/mapper/collection.rb', line 161

def collection
  return nil unless collection?

  @collection ||= target.each.with_index.map do |item, index|
    clone.tap do |mapper|
      mapper.reset_locals!
      mapper.set_target! item
      mapper.item_index = index
    end
  end
end

#collection?Boolean

Returns:

  • (Boolean)


201
202
203
# File 'lib/flatter/mapper/collection.rb', line 201

def collection?
  options[:collection] && item_index.nil?
end

#mapping_namesObject



134
135
136
# File 'lib/flatter/mapper/collection.rb', line 134

def mapping_names
  super.map{ |name| collection? || pluralized? ? name.pluralize : name }
end

#mounting_namesObject



138
139
140
# File 'lib/flatter/mapper/collection.rb', line 138

def mounting_names
  super.map{ |name| pluralized? ? name.pluralize : name }
end

#pluralize!Object



126
127
128
# File 'lib/flatter/mapper/collection.rb', line 126

def pluralize!
  @_pluralized = true
end

#pluralized?Boolean

Returns:

  • (Boolean)


130
131
132
# File 'lib/flatter/mapper/collection.rb', line 130

def pluralized?
  !!@_pluralized
end

#readObject



91
92
93
94
95
96
97
98
99
# File 'lib/flatter/mapper/collection.rb', line 91

def read
  return super unless collection?

  values = collection.map(&:read)

  assert_key_uniqueness!(values)

  {name => values}
end

#write(params) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/flatter/mapper/collection.rb', line 101

def write(params)
  return super unless collection?
  return unless params.key?(name)

  data = extract_data(params)

  assert_collection!(data)

  keys = collection.map(&:key)
  remove_items(keys - data.map{ |p| p[:key] })

  data.each do |params|
    if params.key?(:key)
      update_item(params[:key], params.except(:key))
    else
      add_item(params)
    end
  end
end