lib/roda/endpoints/endpoint/verbs.rb in roda-endpoints-0.1.0 vs lib/roda/endpoints/endpoint/verbs.rb in roda-endpoints-0.2.0
- old
+ new
@@ -1,45 +1,61 @@
# frozen_string_literal: true
-require 'forwardable'
-
class Roda
module Endpoints
# Generic HTTP endpoint abstraction.
class Endpoint
# Accessing data inside of endpoint.
module Verbs
- extend Forwardable
-
- # @param [<Symbol>] only
- # @param [<Symbol>] except
# @param attributes [{Symbol=>Object}]
- def initialize(only: implemented_verbs, except: [], **attributes)
+ def initialize(**attributes)
+ @verbs = verbs_to_implement(**attributes)
+ super(**attributes)
+ end
+
+ # @param only [<Symbol>]
+ # @param except [<Symbol>]
+ def verbs_to_implement(only: implemented_verbs, except: [], **_kwargs)
only = Array(only).flatten
except = Array(except).flatten
if ((unknown_only = only - implemented_verbs) +
(unknown_except = except - implemented_verbs)).any?
params = { only: unknown_only, except: unknown_except }
raise ArgumentError, "unknown verbs in params: #{params}"
end
- @verbs = only - except
- super(**attributes)
+ only - except
end
# @return [<Symbol>]
def implemented_verbs
self.class.verbs.to_a
end
# @return [<Symbol>]
attr_reader :verbs
- def verb(name, **kwargs, &block)
- key = "operations.#{ns}.#{name}"
- container.register key, &block
- singleton_class.verb(name, **kwargs, &container[key])
+ # @param [#to_s] verb
+ # @param [Hash] kwargs
+ # @param [Proc] block
+ def verb(verb, **kwargs, &block)
+ key = "operations.#{ns}.#{verb}"
+ block ||= container[key]
+ singleton_class.verb(verb, **kwargs, &block)
end
- def_delegator :singleton_class, :verb
+
+ def prepare_verbs!
+ return if @verbs_prepared
+ verbs.each do |verb|
+ key = "operations.#{ns}.#{verb}"
+ next if container.key?(key)
+ endpoint = self
+ operation = method(verb)
+ container.register key do |*args|
+ endpoint.instance_exec(*args, &operation)
+ end
+ end
+ @verbs_prepared = true
+ end
end
end
end
end