Skip to content

Instantly share code, notes, and snippets.

@fran-worley
Created April 6, 2018 11:11
Show Gist options
  • Save fran-worley/94b3f8a818871bb8389b16dd387ee2ba to your computer and use it in GitHub Desktop.
Save fran-worley/94b3f8a818871bb8389b16dd387ee2ba to your computer and use it in GitHub Desktop.
input collection formular element
require 'formular/elements'
class InputCollection < Input
set_default :include_hidden, true
html do |element|
concat element.collection.map { |item|
item.to_html(context: :default)
}.join('')
concat element.hidden_tag
end
def hidden_tag
return '' unless options[:include_hidden]
Hidden.(value: "", name: options[:name]).to_s
end
def collection
base_options = collection_base_options
@collection ||= options[:collection].map do |item|
opts = base_options.dup
opts[:value] = item
opts[:id] = if options[:id]
"#{options[:id]}_#{opts[:value]}"
else
"#{attribute_name || options[:name].gsub('[]', '')}_#{opts[:value]}"
end
self.class.(opts)
end
end
private
# append the [] to name so the param comes through correctly
def form_encoded_name
super + '[]'
end
def collection_base_options
opts = attributes.select { |k, v| ![:name, :id, :value, :class].include?(k) }
# FIXME due to class merging, we'll end up with duplicate classes...
opts[:attribute_name] = attribute_name if attribute_name
opts[:builder] = builder if builder
opts[:name] = options[:name] if options[:name] # do we need this??
opts[:include_hidden] = false
opts
end
end # class InputCollection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment