lib/phlexi/form/structure/namespace_collection.rb in phlexi-form-0.2.0 vs lib/phlexi/form/structure/namespace_collection.rb in phlexi-form-0.3.0.rc1
- old
+ new
@@ -4,39 +4,39 @@
module Form
module Structure
class NamespaceCollection < Node
include Enumerable
- def initialize(key, parent:, collection: nil, &)
+ def initialize(key, parent:, collection: nil, &block)
+ raise ArgumentError, "block is required" unless block.present?
+
super(key, parent: parent)
- @namespaces = enumerate(collection)
- each(&) if block_given?
+ @collection = collection
+ @block = block
+ each(&block)
end
- def serialize
- map(&:serialize)
- end
+ def extract_input(params)
+ namespace = build_namespace(0)
+ @block.call(namespace)
- def assign(array)
- # The problem with zip-ing the array is if I need to add new
- # elements to it and wrap it in the namespace.
- zip(array) do |namespace, hash|
- namespace.assign hash
- end
+ inputs = params[key].map { |param| namespace.extract_input([param]) }
+ {key => inputs}
end
+ private
+
def each(&)
- @namespaces.each(&)
+ namespaces.each(&)
end
- private
-
- def enumerate(enumerator)
- Enumerator.new do |y|
- enumerator.each.with_index do |object, key|
- y << build_namespace(key, object: object)
- end
+ # Builds and memoizes namespaces for the collection.
+ #
+ # @return [Array<Hash>] An array of namespace hashes.
+ def namespaces
+ @namespaces ||= @collection.map.with_index do |object, key|
+ build_namespace(key, object: object)
end
end
def build_namespace(index, **)
parent.class.new(index, parent: self, builder_klass: parent.builder_klass, **)