# frozen_string_literal: true module ShibRack # Mixin which provides helper methods for mapping attributes from Rack's `env` module AttributeMapping # Class methods for defining attribute mappings module ClassMethods attr_accessor :attribute_mappings def map_single_value(**mappings) mappings.each do |attr, header| mapper = ->(env) { env[header] } add_attribute_mapping(attr, mapper) end end def map_multi_value(**mappings) mappings.each do |attr, header| mapper = ->(env) { env[header].split(';') } add_attribute_mapping(attr, mapper) end end def add_attribute_mapping(attr, mapper) raise "Conflicting mapping for `#{attr}`" if attribute_mappings[attr] attribute_mappings[attr] = mapper end end def self.included(base) base.extend(ClassMethods) base.attribute_mappings = {} end def map_attributes(env) self.class.attribute_mappings.reduce({}) do |out, (attr, mapper)| out.merge(attr => mapper.call(env)) end end end end