module Eco module API module Organization class NodeClassifications < Eco::Language::Models::Collection # build the shortcuts of Collection attr_collection :id, :name # , :active def initialize(types = [], klass: Ecoportal::API::GraphQL::Base::LocationClassificationType) # rubocop:disable Lint/UnusedMethodArgument @klass = Ecoportal::API::GraphQL::Base::LocationClassificationType @caches_init = false super(types, klass: @klass) init_caches end def ids @items.map(&:id) end def names @items.map(&:name) end def to_id(name) case name when Enumerable name.map do |n| type(n)&.id end.compact else type(name)&.id end end def to_name(id) case id when Enumerable id.map do |n| type(n)&.name end.compact else type(id)&.name end end def type(id_name) self[id_name] end def [](id_name) @by_id[type_id(id_name)] end private def type_name(id_name) key = treat_classication(id_name) val = (@by_id[key] || @by_name[key])&.name treat_classication(val) end def type_id(id_name) key = treat_classication(id_name) val = (@by_name[key] || @by_id[key])&.id treat_classication(val) end def treat_classication(value) return value unless value.is_a?(String) value.strip.gsub(/\W+/, '').downcase end def init_caches return if @caches_init @by_id = @items.to_h { |nc| [treat_classication(nc.id), nc] } @by_name = @items.to_h { |nc| [treat_classication(nc.name), nc] } @caches_init = true end end end end end