Sha256: 4b8ca692809c72c7e4b630dcd0ff94dadbd1b39ee4c0cbe804bdeb8680f237df

Contents?: true

Size: 1.27 KB

Versions: 3

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true

module Grape
  class Router
    # this could be an OpenStruct, but doesn't work in Ruby 2.3.0, see https://bugs.ruby-lang.org/issues/12251
    class AttributeTranslator
      attr_reader :attributes

      ROUTE_ATTRIBUTES = %i[
        prefix
        version
        settings
        format
        description
        http_codes
        headers
        entity
        details
        requirements
        request_method
        namespace
      ].freeze

      ROUTER_ATTRIBUTES = %i[pattern index].freeze

      def initialize(**attributes)
        @attributes = attributes
      end

      (ROUTER_ATTRIBUTES + ROUTE_ATTRIBUTES).each do |attr|
        define_method attr do
          attributes[attr]
        end
      end

      def to_h
        attributes
      end

      def method_missing(method_name, *args)
        if setter?(method_name[-1])
          attributes[method_name[0..]] = *args
        else
          attributes[method_name]
        end
      end

      def respond_to_missing?(method_name, _include_private = false)
        if setter?(method_name[-1])
          true
        else
          @attributes.key?(method_name)
        end
      end

      private

      def setter?(method_name)
        method_name[-1] == '='
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
grape-2.0.0 lib/grape/router/attribute_translator.rb
grape-1.8.0 lib/grape/router/attribute_translator.rb
grape-1.7.1 lib/grape/router/attribute_translator.rb