Class: Grape::Endpoint
- Inherits:
-
Object
- Object
- Grape::Endpoint
- Defined in:
- lib/grape/endpoint.rb
Overview
An Endpoint is the proxy scope in which all routing
blocks are executed. In other words, any methods
on the instance level of this class may be called
from inside a get
, post
, etc.
Instance Attribute Summary collapse
-
#block ⇒ Object
Returns the value of attribute block.
-
#env ⇒ Object
readonly
Returns the value of attribute env.
-
#options ⇒ Object
Returns the value of attribute options.
-
#request ⇒ Object
readonly
Returns the value of attribute request.
-
#settings ⇒ Object
Returns the value of attribute settings.
-
#source ⇒ Object
Returns the value of attribute source.
Class Method Summary collapse
-
.generate_api_method(method_name, &block) ⇒ Proc
private
Create an UnboundMethod that is appropriate for executing an endpoint route.
Instance Method Summary collapse
-
#body(value = nil) ⇒ Object
Allows you to define the response body as something other than the return value.
- #call(env) ⇒ Object
- #call!(env) ⇒ Object
- #compile_path(prepared_path, anchor = true, requirements = {}) ⇒ Object
-
#content_type(val) ⇒ Object
Set response content-type.
-
#cookies ⇒ Object
Set or get a cookie.
-
#declared(params, options = {}) ⇒ Object
A filtering method that will return a hash consisting only of keys that have been declared by a
params
statement. -
#error!(message, status = 403) ⇒ Object
End the request and display an error to the end user with the specified message.
-
#header(key = nil, val = nil) ⇒ Object
Set an individual header or retrieve all headers that have been set.
-
#headers ⇒ Object
Retrieves all available request headers.
-
#initialize(settings, options = {}, &block) ⇒ Endpoint
constructor
A new instance of Endpoint.
- #mount_in(route_set) ⇒ Object
- #namespace ⇒ Object
-
#params ⇒ Object
The parameters passed into the request as well as parsed from URL segments.
- #prepare_path(path) ⇒ Object
- #prepare_routes ⇒ Object
-
#present(object, options = {}) ⇒ Object
Allows you to make use of Grape Entities by setting the response body to the serializable hash of the entity provided in the
:with
option. -
#redirect(url, options = {}) ⇒ Object
Redirect to a new url.
-
#route ⇒ Object
Returns route information for the current request.
- #routes ⇒ Object
-
#status(status = nil) ⇒ Object
Set or retrieve the HTTP status code.
-
#version ⇒ Object
The API version as specified in the URL.
Constructor Details
#initialize(settings, options = {}, &block) ⇒ Endpoint
Returns a new instance of Endpoint.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/grape/endpoint.rb', line 35 def initialize(settings, = {}, &block) @settings = settings if block_given? method_name = [ [:method], settings.gather(:namespace).join("/"), settings.gather(:mount_path).join("/"), Array([:path]).join("/") ].join(" ") @source = block @block = self.class.generate_api_method(method_name, &block) end @options = raise Grape::Exceptions::MissingOption.new(:path) unless .key?(:path) [:path] = Array([:path]) [:path] = ['/'] if [:path].empty? raise Grape::Exceptions::MissingOption.new(:method) unless .key?(:method) [:method] = Array([:method]) [:route_options] ||= {} end |
Instance Attribute Details
#block ⇒ Object
Returns the value of attribute block.
7 8 9 |
# File 'lib/grape/endpoint.rb', line 7 def block @block end |
#env ⇒ Object (readonly)
Returns the value of attribute env.
8 9 10 |
# File 'lib/grape/endpoint.rb', line 8 def env @env end |
#options ⇒ Object
Returns the value of attribute options.
7 8 9 |
# File 'lib/grape/endpoint.rb', line 7 def @options end |
#request ⇒ Object (readonly)
Returns the value of attribute request.
8 9 10 |
# File 'lib/grape/endpoint.rb', line 8 def request @request end |
#settings ⇒ Object
Returns the value of attribute settings.
7 8 9 |
# File 'lib/grape/endpoint.rb', line 7 def settings @settings end |
#source ⇒ Object
Returns the value of attribute source.
7 8 9 |
# File 'lib/grape/endpoint.rb', line 7 def source @source end |
Class Method Details
.generate_api_method(method_name, &block) ⇒ Proc
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Create an UnboundMethod that is appropriate for executing an endpoint route.
The unbound method allows explicit calls to +return+ without raising a +LocalJumpError+. The method will be removed, but a +Proc+ reference to it will be returned. The returned +Proc+ expects a single argument: the instance of +Endpoint+ to bind to the method during the call.
24 25 26 27 28 29 30 31 32 |
# File 'lib/grape/endpoint.rb', line 24 def generate_api_method(method_name, &block) if instance_methods.include?(method_name.to_sym) || instance_methods.include?(method_name.to_s) raise NameError.new("method #{method_name.inspect} already exists and cannot be used as an unbound method name") end define_method(method_name, &block) method = instance_method(method_name) remove_method(method_name) proc { |endpoint_instance| method.bind(endpoint_instance).call } end |
Instance Method Details
#body(value = nil) ⇒ Object
Allows you to define the response body as something other than the return value.
292 293 294 295 296 297 298 |
# File 'lib/grape/endpoint.rb', line 292 def body(value = nil) if value @body = value else @body end end |
#call(env) ⇒ Object
150 151 152 |
# File 'lib/grape/endpoint.rb', line 150 def call(env) dup.call!(env) end |
#call!(env) ⇒ Object
154 155 156 157 158 159 160 161 162 163 |
# File 'lib/grape/endpoint.rb', line 154 def call!(env) env['api.endpoint'] = self if [:app] [:app].call(env) else builder = build_middleware builder.run [:app] || lambda{|env| self.run(env) } builder.call(env) end end |
#compile_path(prepared_path, anchor = true, requirements = {}) ⇒ Object
143 144 145 146 147 148 |
# File 'lib/grape/endpoint.rb', line 143 def compile_path(prepared_path, anchor = true, requirements = {}) = {} [:version] = /#{settings[:version].join('|')}/ if settings[:version] .merge!(requirements) Rack::Mount::Strexp.compile(prepared_path, , %w( / . ? ), anchor) end |
#content_type(val) ⇒ Object
Set response content-type
266 267 268 |
# File 'lib/grape/endpoint.rb', line 266 def content_type(val) header('Content-Type', val) end |
#cookies ⇒ Object
Set or get a cookie
278 279 280 |
# File 'lib/grape/endpoint.rb', line 278 def @cookies ||= Cookies.new end |
#declared(params, options = {}) ⇒ Object
A filtering method that will return a hash
consisting only of keys that have been declared by a
params
statement.
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/grape/endpoint.rb', line 179 def declared(params, = {}) [:include_missing] = true unless .key?(:include_missing) unless settings[:declared_params] raise ArgumentError, "Tried to filter for declared parameters but none exist." end settings[:declared_params].inject({}){|h,k| output_key = [:stringify] ? k.to_s : k.to_sym if params.key?(output_key) || [:include_missing] h[output_key] = params[k] end h } end |
#error!(message, status = 403) ⇒ Object
End the request and display an error to the end user with the specified message.
203 204 205 |
# File 'lib/grape/endpoint.rb', line 203 def error!(, status=403) throw :error, :message => , :status => status end |
#header(key = nil, val = nil) ⇒ Object
Set an individual header or retrieve all headers that have been set.
246 247 248 249 250 251 252 |
# File 'lib/grape/endpoint.rb', line 246 def header(key = nil, val = nil) if key val ? @header[key.to_s] = val : @header.delete(key.to_s) else @header end end |
#headers ⇒ Object
Retrieves all available request headers.
255 256 257 258 259 260 261 262 263 |
# File 'lib/grape/endpoint.rb', line 255 def headers @headers ||= @env.dup.inject({}) { |h, (k, v)| if k.start_with? 'HTTP_' k = k[5..-1].gsub('_', '-').downcase.gsub(/^.|[-_\s]./) { |x| x.upcase } h[k] = v end h } end |
#mount_in(route_set) ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/grape/endpoint.rb', line 63 def mount_in(route_set) if endpoints endpoints.each { |e| e.mount_in(route_set) } else routes.each do |route| methods = [ route.route_method ] if ! settings[:do_not_route_head] && route.route_method == "GET" methods << "HEAD" end methods.each do |method| route_set.add_route(self, { :path_info => route.route_compiled, :request_method => method, }, { :route_info => route }) end end end end |
#namespace ⇒ Object
139 140 141 |
# File 'lib/grape/endpoint.rb', line 139 def namespace Rack::Mount::Utils.normalize_path(settings.stack.map{|s| s[:namespace]}.join('/')) end |
#params ⇒ Object
The parameters passed into the request as well as parsed from URL segments.
167 168 169 170 171 |
# File 'lib/grape/endpoint.rb', line 167 def params @params ||= Hashie::Mash.new. deep_merge(request.params). deep_merge(env['rack.routing_args'] || {}) end |
#prepare_path(path) ⇒ Object
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/grape/endpoint.rb', line 118 def prepare_path(path) parts = [] parts << settings[:mount_path].to_s.split("/") if settings[:mount_path] parts << settings[:root_prefix].to_s.split("/") if settings[:root_prefix] uses_path_versioning = settings[:version] && settings[:version_options][:using] == :path namespace_is_empty = namespace && (namespace.to_s =~ /^\s*$/ || namespace.to_s == '/') path_is_empty = path && (path.to_s =~ /^\s*$/ || path.to_s == '/') parts << ':version' if uses_path_versioning if ! uses_path_versioning || (! namespace_is_empty || ! path_is_empty) parts << namespace.to_s if namespace parts << path.to_s if path format_suffix = '(.:format)' else format_suffix = '(/.:format)' end parts = parts.flatten.select { |part| part != '/' } Rack::Mount::Utils.normalize_path(parts.join('/') + format_suffix) end |
#prepare_routes ⇒ Object
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
# File 'lib/grape/endpoint.rb', line 82 def prepare_routes routes = [] [:method].each do |method| [:path].each do |path| prepared_path = prepare_path(path) anchor = [:route_options][:anchor] anchor = anchor.nil? ? true : anchor requirements = [:route_options][:requirements] || {} path = compile_path(prepared_path, anchor && ![:app], requirements) regex = Rack::Mount::RegexpWithNamedGroups.new(path) path_params = {} # named parameters in the api path named_params = regex.named_captures.map { |nc| nc[0] } - [ 'version', 'format' ] named_params.each { |named_param| path_params[named_param] = "" } # route parameters declared via desc or appended to the api declaration route_params = ([:route_options][:params] || {}) path_params.merge!(route_params) request_method = (method.to_s.upcase unless method == :any) routes << Route.new([:route_options].clone.merge({ :prefix => settings[:root_prefix], :version => settings[:version] ? settings[:version].join('|') : nil, :namespace => namespace, :method => request_method, :path => prepared_path, :params => path_params, :compiled => path, }) ) end end routes end |
#present(object, options = {}) ⇒ Object
Allows you to make use of Grape Entities by setting
the response body to the serializable hash of the
entity provided in the :with
option. This has the
added benefit of automatically passing along environment
and version information to the serialization, making it
very easy to do conditional exposures. See Entity docs
for more info.
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
# File 'lib/grape/endpoint.rb', line 315 def present(object, = {}) entity_class = .delete(:with) # auto-detect the entity from the first object in the collection object_instance = object.is_a?(Array) ? object.first : object object_instance.class.ancestors.each do |potential| entity_class ||= (settings[:representations] || {})[potential] end entity_class ||= object_instance.class.const_get(:Entity) if object_instance.class.const_defined?(:Entity) root = .delete(:root) representation = if entity_class = {:env => env} [:version] = env['api.version'] if env['api.version'] entity_class.represent(object, .merge()) else object end representation = { root => representation } if root body representation end |
#redirect(url, options = {}) ⇒ Object
Redirect to a new url.
212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
# File 'lib/grape/endpoint.rb', line 212 def redirect(url, = {}) = {:permanent => false }.merge() if [:permanent] status 301 else if env['HTTP_VERSION'] == 'HTTP/1.1' && request.request_method.to_s.upcase != "GET" status 303 else status 302 end end header "Location", url body "" end |
#route ⇒ Object
Returns route information for the current request.
349 350 351 |
# File 'lib/grape/endpoint.rb', line 349 def route env["rack.routing_args"][:route_info] end |
#routes ⇒ Object
59 60 61 |
# File 'lib/grape/endpoint.rb', line 59 def routes @routes ||= endpoints ? endpoints.collect(&:routes).flatten : prepare_routes end |
#status(status = nil) ⇒ Object
Set or retrieve the HTTP status code.
230 231 232 233 234 235 236 237 238 239 240 241 242 |
# File 'lib/grape/endpoint.rb', line 230 def status(status = nil) if status @status = status else return @status if @status case request.request_method.to_s.upcase when 'POST' 201 else 200 end end end |
#version ⇒ Object
The API version as specified in the URL.
196 |
# File 'lib/grape/endpoint.rb', line 196 def version; env['api.version'] end |