Sha256: c7f6f2f0afb6f194a759ce66f1fd15be7c9f3f306684cff879baa06543206b44

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

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

            define_singleton_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.2.2 lib/routemaster/responses/hateoas_response.rb