Sha256: f180292e402ba4e3aed2fc55959484a333a07883caff0feea816dd9dc1e598ee

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

require 'faraday_middleware'
require 'routemaster/api_client'
require 'routemaster/responses/hateoas_response'
require 'routemaster/resources/rest_resource'
require 'forwardable'
require 'json'

module Routemaster
  module Responses
    class HateoasResponse
      extend Forwardable

      attr_reader :response
      def_delegators :@response, :body, :status, :headers, :success?

      def initialize(response, client: nil)
        @response = response
        @client = client || Routemaster::APIClient.new(response_class: Routemaster::Responses::HateoasResponse)
      end

      def method_missing(m, *args, &block)
        method_name = m.to_s
        normalized_method_name = method_name == '_self' ? 'self' : method_name

        if _links.keys.include?(normalized_method_name)
          unless respond_to?(method_name)
            resource = Resources::RestResource.new(_links[normalized_method_name]['href'], client: @client)

            self.class.send(:define_method, method_name) do |*m_args|
              resource
            end

            resource
          end
        else
          super
        end
      end

      def body_without_links
        body.reject { |key, _| ['_links'].include?(key) }
      end

      private

      def _links
        @links ||= @response.body.fetch('_links', {})
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
routemaster-drain-2.0.0 lib/routemaster/responses/hateoas_response.rb