Sha256: 9d5bf78f8d0d68510ce16cd6650aac2d50eaa5acc6f4fe526f4c8b0f880f24a6

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 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) { 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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
shib-rack-0.1.0 lib/shib_rack/attribute_mapping.rb