Sha256: 33a8233f4730c66cc3352b5b7bff182f5f6b5be302f28d1739569a93524b90af

Contents?: true

Size: 1.39 KB

Versions: 1

Compression:

Stored size: 1.39 KB

Contents

module GrapePathHelpers
  # methods to extend Grape::Endpoint so that calls
  # to unknown methods will look for a route with a matching
  # helper function name
  module NamedRouteMatcher
    def method_missing(method_id, *args, **kwargs)
      return super unless method_id.to_s =~ /_path$/

      success, result = call_path_method(method_id, *args, **kwargs)

      if success
        result
      else
        super
      end
    end

    def call_path_method(method_id, *arguments)
      segments = arguments.first || {}

      route = Grape::API::Instance.decorated_routes.detect do |r|
        route_match?(r, method_id, segments)
      end

      return false unless route

      [true, route.send(method_id, *arguments)]
    end

    def respond_to_missing?(method_name, _include_private = false)
      return super unless method_name =~ /_path$/

      Grape::API::Instance.decorated_routes.detect do |route|
        return true if route.respond_to?(method_name)
      end

      super
    end

    def route_match?(route, method_name, segments)
      return false unless route.respond_to?(method_name)
      # rubocop:disable Metrics/LineLength
      raise ArgumentError, 'Helper options must be a hash' unless segments.is_a?(Hash)
      # rubocop:enable Metrics/LineLength
      requested_segments = segments.keys.map(&:to_s)
      route.uses_segments_in_path_helper?(requested_segments)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
grape-path-helpers-1.6.0 lib/grape-path-helpers/named_route_matcher.rb