Sha256: a2bd6c4e96b12e37d8301f858a1ae4d23df13ffd46dbe22c75a2db8fda227522

Contents?: true

Size: 1.21 KB

Versions: 2

Compression:

Stored size: 1.21 KB

Contents

# 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) { parse_multi_value(env[header]) }
          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

      def parse_multi_value(value)
        value.split(/(?<!\\);/).map { |x| x.gsub('\;', ';') }
      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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
shib-rack-0.3.0 lib/shib_rack/attribute_mapping.rb
shib-rack-0.2.0 lib/shib_rack/attribute_mapping.rb