module Ecoportal module API class V2 class Page class Component class SelectionOptions < Ecoportal::API::Common::Content::CollectionModel class_resolver :option_class, "Ecoportal::API::V2::Page::Component::SelectionOption" self.klass = :option_class self.order_key = :weight def component self._parent end def ooze component.ooze end def add(value:, name: nil, pos: NOT_USED, before: NOT_USED, after: NOT_USED) opt_doc = items_class.new_doc upsert!(opt_doc, pos: pos, before: before, after: after) do |option| option.name = name option.value = value if prev = previous_option(option) option.weight = prev.weight end yield(option) if block_given? fix_weights! end end def find_option(value_name, by_name: false) if by_name opt = self.find {|opt| same_string?(opt.name, value_name)} else opt = self.find {|opt| opt.value == value_name} end end def ordered self.sort_by.with_index do |option, index| [option.weight, index] end end # @param name [Boolean] whether or not the values of the `Hash` should be the `names` # @return [Hash] of **key** _value_ and **value**: # 1. _option_ if `name` is `false` # 2. _name_ if `name` is `true` def by_value(name: false) hash do |option| name ? option.name : option end end # @param value [Boolean] whether or not the values of the `Hash` should be the `values` # @return [Hash] of **key** _name_ and **value**: # 1. _option_ if `value` is `false` # 2. _value_ if `value` is `true` def by_name(value: false) hash(by_name: true) do |option| value ? option.value : option end end def hash(elems = ordered, by_name: false) elems.each_with_object({}) do |option, hash| key = by_name ? option.name : option.value hash[key] = block_given?? yield(option) : option end end private def fix_weights! ordered.each_with_index do |option, index| option.weight = index end end def previous_option(value) opts = ordered pos = opts.index(value) - 1 return if pos < 0 opts[pos] end end end end end end end