lib/ecoportal/api/v2/page/component/selection_field.rb in ecoportal-api-v2-0.8.8 vs lib/ecoportal/api/v2/page/component/selection_field.rb in ecoportal-api-v2-0.8.9
- old
+ new
@@ -2,12 +2,12 @@
module API
class V2
class Page
class Component
class SelectionField < Page::Component
- passthrough :multiple, :flat
- passthrough :other, :other_desc
+ passboolean :multiple, :flat, :other
+ passthrough :other_desc
passthrough :data_type
embeds_many :options, klass: "Ecoportal::API::V2::Page::Component::SelectionOption", order_key: :weight
def numeric!(&block)
@@ -42,11 +42,11 @@
else
selected&.value
end
end
- def add_option(name:, value:, pos: NOT_USED, before: NOT_USED, after: NOT_USED)
+ def add_option(value:, name: nil, pos: NOT_USED, before: NOT_USED, after: NOT_USED)
opt_doc = options.items_class.new_doc
options.upsert!(opt_doc, pos: pos, before: before, after: after) do |option|
option.name = name
option.value = value
if prev = previous_option(option)
@@ -61,10 +61,66 @@
options.each_with_index.sort_by do |option, index|
(option.weight >= 9999) ? [index, index] : [option.weight, index]
end.map(&:first)
end
+ # Quick config helper
+ # @param conf [Symbol, Array<Symbol>]
+ # - `:flat` to display in flat mode
+ # - `:multiple` to allow multiple selection
+ # - `:single` to set to singular selection
+ # - `:other` to enable `other` button
+ # - `:options` to add options (`Hash<value, name>`)
+ # - `:type` to define the type
+ # - `:num`
+ # - `:str`
+ def configure(*conf)
+ conf.each_with_object([]) do |cnf, unused|
+ case cnf
+ when :flat
+ self.flat = true
+ when :multiple
+ self.multiple = true
+ when :single
+ self.multiple = false
+ when :other
+ self.other = true
+ when Hash
+ supported = [:flat, :options, :type]
+ unless (rest = hash_except(cnf.dup, *supported)).empty?
+ unused.push(rest)
+ end
+
+ if cnf.key?(:flat) then self.flat = cnf[:flat] end
+ if cnf.key?(:options)
+ if opts = cnf[:options]
+ configure_options opts
+ end
+ end
+ if cnf.key?(:type)
+ if cnf[:type] == :str
+ self.text!
+ elsif cnf[:type] == :num
+ self.numeric!
+ else
+ # Unknown type
+ end
+ end
+ else
+ unused.push(cnf)
+ end
+ end.yield_self do |unused|
+ super(*unused)
+ end
+ end
+
private
+
+ def configure_options(opts)
+ opts.each do |val, nm|
+ add_option(value: val, name: nm)
+ end
+ end
def fix_option_weights!
ordered_options.each_with_index do |option, index|
option.weight = index
end