grape 0.5.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +1223 -164
  3. data/CONTRIBUTING.md +148 -0
  4. data/LICENSE +1 -1
  5. data/README.md +3531 -675
  6. data/UPGRADING.md +1851 -0
  7. data/grape.gemspec +26 -32
  8. data/grape.png +0 -0
  9. data/lib/grape/api/instance.rb +194 -0
  10. data/lib/grape/api.rb +110 -485
  11. data/lib/grape/content_types.rb +28 -0
  12. data/lib/grape/cookies.rb +32 -25
  13. data/lib/grape/declared_params_handler.rb +118 -0
  14. data/lib/grape/dry_types.rb +54 -0
  15. data/lib/grape/dsl/callbacks.rb +19 -0
  16. data/lib/grape/dsl/declared.rb +35 -0
  17. data/lib/grape/dsl/desc.rb +65 -0
  18. data/lib/grape/dsl/headers.rb +21 -0
  19. data/lib/grape/dsl/helpers.rb +103 -0
  20. data/lib/grape/dsl/inside_route.rb +293 -0
  21. data/lib/grape/dsl/logger.rb +19 -0
  22. data/lib/grape/dsl/middleware.rb +36 -0
  23. data/lib/grape/dsl/parameters.rb +239 -0
  24. data/lib/grape/dsl/request_response.rb +168 -0
  25. data/lib/grape/dsl/routing.rb +288 -0
  26. data/lib/grape/dsl/settings.rb +67 -0
  27. data/lib/grape/dsl/validations.rb +51 -0
  28. data/lib/grape/endpoint.rb +287 -386
  29. data/lib/grape/env.rb +20 -0
  30. data/lib/grape/error_formatter/base.rb +56 -19
  31. data/lib/grape/error_formatter/json.rb +18 -7
  32. data/lib/grape/error_formatter/serializable_hash.rb +7 -0
  33. data/lib/grape/error_formatter/txt.rb +14 -11
  34. data/lib/grape/error_formatter/xml.rb +5 -11
  35. data/lib/grape/error_formatter.rb +15 -0
  36. data/lib/grape/exceptions/base.rb +31 -47
  37. data/lib/grape/exceptions/incompatible_option_values.rb +11 -0
  38. data/lib/grape/exceptions/invalid_accept_header.rb +11 -0
  39. data/lib/grape/exceptions/invalid_formatter.rb +3 -5
  40. data/lib/grape/exceptions/invalid_message_body.rb +11 -0
  41. data/lib/grape/exceptions/invalid_response.rb +11 -0
  42. data/lib/grape/exceptions/invalid_version_header.rb +11 -0
  43. data/lib/grape/exceptions/invalid_versioner_option.rb +3 -6
  44. data/lib/grape/exceptions/invalid_with_option_for_represent.rb +3 -7
  45. data/lib/grape/exceptions/method_not_allowed.rb +11 -0
  46. data/lib/grape/exceptions/missing_group_type.rb +11 -0
  47. data/lib/grape/exceptions/missing_mime_type.rb +3 -6
  48. data/lib/grape/exceptions/missing_vendor_option.rb +3 -5
  49. data/lib/grape/exceptions/request_error.rb +11 -0
  50. data/lib/grape/exceptions/unknown_auth_strategy.rb +11 -0
  51. data/lib/grape/exceptions/unknown_parameter.rb +11 -0
  52. data/lib/grape/exceptions/unknown_params_builder.rb +11 -0
  53. data/lib/grape/exceptions/unknown_validator.rb +3 -4
  54. data/lib/grape/exceptions/unsupported_group_type.rb +11 -0
  55. data/lib/grape/exceptions/validation.rb +20 -8
  56. data/lib/grape/exceptions/validation_array_errors.rb +14 -0
  57. data/lib/grape/exceptions/validation_errors.rb +59 -0
  58. data/lib/grape/formatter/base.rb +9 -26
  59. data/lib/grape/formatter/json.rb +6 -7
  60. data/lib/grape/formatter/serializable_hash.rb +24 -20
  61. data/lib/grape/formatter/txt.rb +5 -7
  62. data/lib/grape/formatter/xml.rb +6 -7
  63. data/lib/grape/formatter.rb +17 -0
  64. data/lib/grape/json.rb +10 -0
  65. data/lib/grape/locale/en.yml +47 -20
  66. data/lib/grape/middleware/auth/base.rb +25 -0
  67. data/lib/grape/middleware/auth/dsl.rb +38 -0
  68. data/lib/grape/middleware/auth/strategies.rb +25 -0
  69. data/lib/grape/middleware/auth/strategy_info.rb +15 -0
  70. data/lib/grape/middleware/base.rb +73 -19
  71. data/lib/grape/middleware/error.rb +104 -44
  72. data/lib/grape/middleware/filter.rb +5 -3
  73. data/lib/grape/middleware/formatter.rb +115 -105
  74. data/lib/grape/middleware/globals.rb +14 -0
  75. data/lib/grape/middleware/stack.rb +110 -0
  76. data/lib/grape/middleware/versioner/accept_version_header.rb +11 -40
  77. data/lib/grape/middleware/versioner/base.rb +76 -0
  78. data/lib/grape/middleware/versioner/header.rb +61 -78
  79. data/lib/grape/middleware/versioner/param.rb +9 -21
  80. data/lib/grape/middleware/versioner/path.rb +16 -31
  81. data/lib/grape/middleware/versioner.rb +10 -15
  82. data/lib/grape/namespace.rb +39 -10
  83. data/lib/grape/params_builder/base.rb +20 -0
  84. data/lib/grape/params_builder/hash.rb +11 -0
  85. data/lib/grape/params_builder/hash_with_indifferent_access.rb +11 -0
  86. data/lib/grape/params_builder/hashie_mash.rb +11 -0
  87. data/lib/grape/params_builder.rb +15 -0
  88. data/lib/grape/parser/base.rb +9 -24
  89. data/lib/grape/parser/json.rb +8 -7
  90. data/lib/grape/parser/xml.rb +8 -7
  91. data/lib/grape/parser.rb +15 -0
  92. data/lib/grape/path.rb +76 -0
  93. data/lib/grape/presenters/presenter.rb +11 -0
  94. data/lib/grape/railtie.rb +9 -0
  95. data/lib/grape/request.rb +182 -0
  96. data/lib/grape/router/base_route.rb +48 -0
  97. data/lib/grape/router/greedy_route.rb +26 -0
  98. data/lib/grape/router/pattern.rb +67 -0
  99. data/lib/grape/router/route.rb +58 -0
  100. data/lib/grape/router.rb +167 -0
  101. data/lib/grape/serve_stream/file_body.rb +36 -0
  102. data/lib/grape/serve_stream/sendfile_response.rb +21 -0
  103. data/lib/grape/serve_stream/stream_response.rb +23 -0
  104. data/lib/grape/util/api_description.rb +58 -0
  105. data/lib/grape/util/base_inheritable.rb +46 -0
  106. data/lib/grape/util/cache.rb +18 -0
  107. data/lib/grape/util/deep_freeze.rb +35 -0
  108. data/lib/grape/util/endpoint_configuration.rb +8 -0
  109. data/lib/grape/util/header.rb +13 -0
  110. data/lib/grape/util/inheritable_setting.rb +107 -0
  111. data/lib/grape/util/inheritable_values.rb +29 -0
  112. data/lib/grape/util/lazy/block.rb +29 -0
  113. data/lib/grape/util/lazy/value.rb +38 -0
  114. data/lib/grape/util/lazy/value_array.rb +21 -0
  115. data/lib/grape/util/lazy/value_enumerable.rb +34 -0
  116. data/lib/grape/util/lazy/value_hash.rb +21 -0
  117. data/lib/grape/util/media_type.rb +70 -0
  118. data/lib/grape/util/registry.rb +27 -0
  119. data/lib/grape/util/reverse_stackable_values.rb +15 -0
  120. data/lib/grape/util/stackable_values.rb +36 -0
  121. data/lib/grape/util/translation.rb +42 -0
  122. data/lib/grape/validations/attributes_iterator.rb +77 -0
  123. data/lib/grape/validations/contract_scope.rb +28 -0
  124. data/lib/grape/validations/multiple_attributes_iterator.rb +13 -0
  125. data/lib/grape/validations/param_scope_tracker.rb +57 -0
  126. data/lib/grape/validations/params_documentation.rb +50 -0
  127. data/lib/grape/validations/params_scope.rb +529 -0
  128. data/lib/grape/validations/single_attribute_iterator.rb +26 -0
  129. data/lib/grape/validations/types/array_coercer.rb +60 -0
  130. data/lib/grape/validations/types/custom_type_coercer.rb +164 -0
  131. data/lib/grape/validations/types/custom_type_collection_coercer.rb +56 -0
  132. data/lib/grape/validations/types/dry_type_coercer.rb +59 -0
  133. data/lib/grape/validations/types/file.rb +31 -0
  134. data/lib/grape/validations/types/invalid_value.rb +17 -0
  135. data/lib/grape/validations/types/json.rb +71 -0
  136. data/lib/grape/validations/types/multiple_type_coercer.rb +57 -0
  137. data/lib/grape/validations/types/primitive_coercer.rb +46 -0
  138. data/lib/grape/validations/types/set_coercer.rb +35 -0
  139. data/lib/grape/validations/types/variant_collection_coercer.rb +51 -0
  140. data/lib/grape/validations/types.rb +198 -0
  141. data/lib/grape/validations/validators/all_or_none_of_validator.rb +19 -0
  142. data/lib/grape/validations/validators/allow_blank_validator.rb +25 -0
  143. data/lib/grape/validations/validators/as_validator.rb +14 -0
  144. data/lib/grape/validations/validators/at_least_one_of_validator.rb +18 -0
  145. data/lib/grape/validations/validators/base.rb +158 -0
  146. data/lib/grape/validations/validators/coerce_validator.rb +55 -0
  147. data/lib/grape/validations/validators/contract_scope_validator.rb +45 -0
  148. data/lib/grape/validations/validators/default_validator.rb +31 -0
  149. data/lib/grape/validations/validators/exactly_one_of_validator.rb +24 -0
  150. data/lib/grape/validations/validators/except_values_validator.rb +33 -0
  151. data/lib/grape/validations/validators/length_validator.rb +48 -0
  152. data/lib/grape/validations/validators/multiple_params_base.rb +34 -0
  153. data/lib/grape/validations/validators/mutually_exclusive_validator.rb +18 -0
  154. data/lib/grape/validations/validators/presence_validator.rb +17 -0
  155. data/lib/grape/validations/validators/regexp_validator.rb +24 -0
  156. data/lib/grape/validations/validators/same_as_validator.rb +20 -0
  157. data/lib/grape/validations/validators/values_validator.rb +68 -0
  158. data/lib/grape/validations.rb +10 -226
  159. data/lib/grape/version.rb +4 -1
  160. data/lib/grape/xml.rb +10 -0
  161. data/lib/grape.rb +79 -77
  162. metadata +160 -306
  163. data/.gitignore +0 -38
  164. data/.rspec +0 -2
  165. data/.travis.yml +0 -9
  166. data/.yardopts +0 -2
  167. data/Gemfile +0 -19
  168. data/Guardfile +0 -15
  169. data/Rakefile +0 -64
  170. data/lib/grape/exceptions/missing_option.rb +0 -13
  171. data/lib/grape/exceptions/unknown_options.rb +0 -14
  172. data/lib/grape/http/request.rb +0 -28
  173. data/lib/grape/middleware/auth/basic.rb +0 -30
  174. data/lib/grape/middleware/auth/digest.rb +0 -30
  175. data/lib/grape/middleware/auth/oauth2.rb +0 -72
  176. data/lib/grape/route.rb +0 -23
  177. data/lib/grape/util/content_types.rb +0 -17
  178. data/lib/grape/util/deep_merge.rb +0 -23
  179. data/lib/grape/util/hash_stack.rb +0 -120
  180. data/lib/grape/validations/coerce.rb +0 -62
  181. data/lib/grape/validations/default.rb +0 -24
  182. data/lib/grape/validations/presence.rb +0 -12
  183. data/lib/grape/validations/regexp.rb +0 -14
  184. data/spec/grape/api_spec.rb +0 -2129
  185. data/spec/grape/endpoint_spec.rb +0 -605
  186. data/spec/grape/entity_spec.rb +0 -281
  187. data/spec/grape/exceptions/invalid_formatter_spec.rb +0 -18
  188. data/spec/grape/exceptions/invalid_versioner_option_spec.rb +0 -18
  189. data/spec/grape/exceptions/missing_mime_type_spec.rb +0 -24
  190. data/spec/grape/exceptions/missing_option_spec.rb +0 -18
  191. data/spec/grape/exceptions/unknown_options_spec.rb +0 -18
  192. data/spec/grape/exceptions/unknown_validator_spec.rb +0 -18
  193. data/spec/grape/middleware/auth/basic_spec.rb +0 -31
  194. data/spec/grape/middleware/auth/digest_spec.rb +0 -47
  195. data/spec/grape/middleware/auth/oauth2_spec.rb +0 -90
  196. data/spec/grape/middleware/base_spec.rb +0 -63
  197. data/spec/grape/middleware/error_spec.rb +0 -49
  198. data/spec/grape/middleware/exception_spec.rb +0 -164
  199. data/spec/grape/middleware/formatter_spec.rb +0 -244
  200. data/spec/grape/middleware/versioner/accept_version_header_spec.rb +0 -121
  201. data/spec/grape/middleware/versioner/header_spec.rb +0 -277
  202. data/spec/grape/middleware/versioner/param_spec.rb +0 -58
  203. data/spec/grape/middleware/versioner/path_spec.rb +0 -44
  204. data/spec/grape/middleware/versioner_spec.rb +0 -22
  205. data/spec/grape/util/hash_stack_spec.rb +0 -133
  206. data/spec/grape/validations/coerce_spec.rb +0 -143
  207. data/spec/grape/validations/default_spec.rb +0 -67
  208. data/spec/grape/validations/presence_spec.rb +0 -144
  209. data/spec/grape/validations/regexp_spec.rb +0 -33
  210. data/spec/grape/validations/zh-CN.yml +0 -9
  211. data/spec/grape/validations_spec.rb +0 -217
  212. data/spec/shared/versioning_examples.rb +0 -121
  213. data/spec/spec_helper.rb +0 -25
  214. data/spec/support/basic_auth_encode_helpers.rb +0 -4
  215. data/spec/support/versioned_helpers.rb +0 -48
@@ -0,0 +1,168 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module DSL
5
+ module RequestResponse
6
+ # Specify the default format for the API's serializers.
7
+ # May be `:json` or `:txt` (default).
8
+ def default_format(new_format = nil)
9
+ return inheritable_setting.namespace_inheritable[:default_format] if new_format.nil?
10
+
11
+ inheritable_setting.namespace_inheritable[:default_format] = new_format.to_sym
12
+ end
13
+
14
+ # Specify the format for the API's serializers.
15
+ # May be `:json`, `:xml`, `:txt`, etc.
16
+ def format(new_format = nil)
17
+ return inheritable_setting.namespace_inheritable[:format] if new_format.nil?
18
+
19
+ symbolic_new_format = new_format.to_sym
20
+ inheritable_setting.namespace_inheritable[:format] = symbolic_new_format
21
+ inheritable_setting.namespace_inheritable[:default_error_formatter] = Grape::ErrorFormatter.formatter_for(symbolic_new_format)
22
+
23
+ content_type = content_types[symbolic_new_format]
24
+ raise Grape::Exceptions::MissingMimeType.new(new_format) unless content_type
25
+
26
+ inheritable_setting.namespace_stackable[:content_types] = { symbolic_new_format => content_type }
27
+ end
28
+
29
+ # Specify a custom formatter for a content-type.
30
+ def formatter(content_type, new_formatter)
31
+ inheritable_setting.namespace_stackable[:formatters] = { content_type.to_sym => new_formatter }
32
+ end
33
+
34
+ # Specify a custom parser for a content-type.
35
+ def parser(content_type, new_parser)
36
+ inheritable_setting.namespace_stackable[:parsers] = { content_type.to_sym => new_parser }
37
+ end
38
+
39
+ # Specify a default error formatter.
40
+ def default_error_formatter(new_formatter_name = nil)
41
+ return inheritable_setting.namespace_inheritable[:default_error_formatter] if new_formatter_name.nil?
42
+
43
+ new_formatter = Grape::ErrorFormatter.formatter_for(new_formatter_name)
44
+ inheritable_setting.namespace_inheritable[:default_error_formatter] = new_formatter
45
+ end
46
+
47
+ def error_formatter(format, options)
48
+ formatter = if options.is_a?(Hash) && options.key?(:with)
49
+ options[:with]
50
+ else
51
+ options
52
+ end
53
+
54
+ inheritable_setting.namespace_stackable[:error_formatters] = { format.to_sym => formatter }
55
+ end
56
+
57
+ # Specify additional content-types, e.g.:
58
+ # content_type :xls, 'application/vnd.ms-excel'
59
+ def content_type(key, val)
60
+ inheritable_setting.namespace_stackable[:content_types] = { key.to_sym => val }
61
+ end
62
+
63
+ # All available content types.
64
+ def content_types
65
+ c_types = inheritable_setting.namespace_stackable_with_hash(:content_types)
66
+ Grape::ContentTypes.content_types_for c_types
67
+ end
68
+
69
+ # Specify the default status code for errors.
70
+ def default_error_status(new_status = nil)
71
+ return inheritable_setting.namespace_inheritable[:default_error_status] if new_status.nil?
72
+
73
+ inheritable_setting.namespace_inheritable[:default_error_status] = new_status
74
+ end
75
+
76
+ # Allows you to rescue certain exceptions that occur to return
77
+ # a grape error rather than raising all the way to the
78
+ # server level.
79
+ #
80
+ # @example Rescue from custom exceptions
81
+ # class ExampleAPI < Grape::API
82
+ # class CustomError < StandardError; end
83
+ #
84
+ # rescue_from CustomError
85
+ # end
86
+ #
87
+ # @overload rescue_from(*exception_classes, **options)
88
+ # @param [Array] exception_classes A list of classes that you want to rescue, or
89
+ # the symbol :all to rescue from all exceptions.
90
+ # @param [Block] block Execution block to handle the given exception.
91
+ # @param [Hash] options Options for the rescue usage.
92
+ # @option options [Boolean] :backtrace Include a backtrace in the rescue response.
93
+ # @option options [Boolean] :rescue_subclasses Also rescue subclasses of exception classes
94
+ # @param [Proc] handler Execution proc to handle the given exception as an
95
+ # alternative to passing a block.
96
+ def rescue_from(*args, **options, &block)
97
+ if args.last.is_a?(Proc)
98
+ handler = args.pop
99
+ elsif block
100
+ handler = block
101
+ end
102
+
103
+ raise ArgumentError, 'both :with option and block cannot be passed' if block && options.key?(:with)
104
+
105
+ handler ||= extract_with(options)
106
+
107
+ if args.include?(:all)
108
+ inheritable_setting.namespace_inheritable[:rescue_all] = true
109
+ inheritable_setting.namespace_inheritable[:all_rescue_handler] = handler
110
+ elsif args.include?(:grape_exceptions)
111
+ inheritable_setting.namespace_inheritable[:rescue_all] = true
112
+ inheritable_setting.namespace_inheritable[:rescue_grape_exceptions] = true
113
+ inheritable_setting.namespace_inheritable[:grape_exceptions_rescue_handler] = handler
114
+ else
115
+ handler_type =
116
+ case options[:rescue_subclasses]
117
+ when nil, true
118
+ :rescue_handlers
119
+ else
120
+ :base_only_rescue_handlers
121
+ end
122
+
123
+ inheritable_setting.namespace_reverse_stackable[handler_type] = args.to_h { |arg| [arg, handler] }
124
+ end
125
+
126
+ inheritable_setting.namespace_stackable[:rescue_options] = options
127
+ end
128
+
129
+ # Allows you to specify a default representation entity for a
130
+ # class. This allows you to map your models to their respective
131
+ # entities once and then simply call `present` with the model.
132
+ #
133
+ # @example
134
+ # class ExampleAPI < Grape::API
135
+ # represent User, with: Entity::User
136
+ #
137
+ # get '/me' do
138
+ # present current_user # with: Entity::User is assumed
139
+ # end
140
+ # end
141
+ #
142
+ # Note that Grape will automatically go up the class ancestry to
143
+ # try to find a representing entity, so if you, for example, define
144
+ # an entity to represent `Object` then all presented objects will
145
+ # bubble up and utilize the entity provided on that `represent` call.
146
+ #
147
+ # @param model_class [Class] The model class that will be represented.
148
+ # @option options [Class] :with The entity class that will represent the model.
149
+ def represent(model_class, options)
150
+ raise Grape::Exceptions::InvalidWithOptionForRepresent.new unless options[:with].is_a?(Class)
151
+
152
+ inheritable_setting.namespace_stackable[:representations] = { model_class => options[:with] }
153
+ end
154
+
155
+ private
156
+
157
+ def extract_with(options)
158
+ return unless options.key?(:with)
159
+
160
+ with_option = options.delete(:with)
161
+ return with_option if with_option.instance_of?(Proc)
162
+ return with_option.to_sym if with_option.instance_of?(Symbol) || with_option.instance_of?(String)
163
+
164
+ raise ArgumentError, "with: #{with_option.class}, expected Symbol, String or Proc"
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,288 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module DSL
5
+ module Routing
6
+ attr_reader :endpoints
7
+
8
+ def given(conditional_option, &)
9
+ return unless conditional_option
10
+
11
+ mounted(&)
12
+ end
13
+
14
+ def mounted(&block)
15
+ evaluate_as_instance_with_configuration(block, lazy: true)
16
+ end
17
+
18
+ def cascade(value = nil)
19
+ return inheritable_setting.namespace_inheritable.key?(:cascade) ? !inheritable_setting.namespace_inheritable[:cascade].nil? : true if value.nil?
20
+
21
+ inheritable_setting.namespace_inheritable[:cascade] = value
22
+ end
23
+
24
+ # Specify an API version.
25
+ #
26
+ # @example API with legacy support.
27
+ # class MyAPI < Grape::API
28
+ # version 'v2'
29
+ #
30
+ # get '/main' do
31
+ # {some: 'data'}
32
+ # end
33
+ #
34
+ # version 'v1' do
35
+ # get '/main' do
36
+ # {legacy: 'data'}
37
+ # end
38
+ # end
39
+ # end
40
+ #
41
+ def version(*args, **options, &block)
42
+ if args.any?
43
+ options = options.reverse_merge(using: :path)
44
+ requested_versions = args.flatten.map(&:to_s)
45
+
46
+ raise Grape::Exceptions::MissingVendorOption.new if options[:using] == :header && !options.key?(:vendor)
47
+
48
+ @versions = versions | requested_versions
49
+
50
+ if block
51
+ within_namespace do
52
+ inheritable_setting.namespace_inheritable[:version] = requested_versions
53
+ inheritable_setting.namespace_inheritable[:version_options] = options
54
+
55
+ instance_eval(&block)
56
+ end
57
+ else
58
+ inheritable_setting.namespace_inheritable[:version] = requested_versions
59
+ inheritable_setting.namespace_inheritable[:version_options] = options
60
+ end
61
+ end
62
+
63
+ @versions&.last
64
+ end
65
+
66
+ # Define a root URL prefix for your entire API.
67
+ def prefix(prefix = nil)
68
+ return inheritable_setting.namespace_inheritable[:root_prefix] if prefix.nil?
69
+
70
+ inheritable_setting.namespace_inheritable[:root_prefix] = prefix.to_s
71
+ end
72
+
73
+ # Create a scope without affecting the URL.
74
+ #
75
+ # @param _name [Symbol] Purely placebo, just allows to name the scope to
76
+ # make the code more readable.
77
+ def scope(_name = nil, &block)
78
+ within_namespace do
79
+ nest(block)
80
+ end
81
+ end
82
+
83
+ def build_with(build_with)
84
+ inheritable_setting.namespace_inheritable[:build_params_with] = build_with
85
+ end
86
+
87
+ # Do not route HEAD requests to GET requests automatically.
88
+ def do_not_route_head!
89
+ inheritable_setting.namespace_inheritable[:do_not_route_head] = true
90
+ end
91
+
92
+ # Do not automatically route OPTIONS.
93
+ def do_not_route_options!
94
+ inheritable_setting.namespace_inheritable[:do_not_route_options] = true
95
+ end
96
+
97
+ def lint!
98
+ inheritable_setting.namespace_inheritable[:lint] = true
99
+ end
100
+
101
+ def do_not_document!
102
+ inheritable_setting.namespace_inheritable[:do_not_document] = true
103
+ end
104
+
105
+ def mount(mounts, *opts)
106
+ mounts = { mounts => '/' } unless mounts.respond_to?(:each_pair)
107
+ mounts.each_pair do |app, path|
108
+ if app.respond_to?(:mount_instance)
109
+ opts_with = opts.any? ? opts.first[:with] : {}
110
+ mount({ app.mount_instance(configuration: opts_with) => path }, *opts)
111
+ next
112
+ end
113
+ in_setting = inheritable_setting
114
+
115
+ if app.respond_to?(:inheritable_setting, true)
116
+ mount_path = Grape::Router.normalize_path(path)
117
+ app.top_level_setting.namespace_stackable[:mount_path] = mount_path
118
+
119
+ app.inherit_settings(inheritable_setting)
120
+
121
+ in_setting = app.top_level_setting
122
+
123
+ app.change!
124
+ change!
125
+ end
126
+
127
+ # When trying to mount multiple times the same endpoint, remove the previous ones
128
+ # from the list of endpoints if refresh_already_mounted parameter is true
129
+ refresh_already_mounted = opts.any? ? opts.first[:refresh_already_mounted] : false
130
+ if refresh_already_mounted && !endpoints.empty?
131
+ endpoints.delete_if do |endpoint|
132
+ endpoint.options[:app].to_s == app.to_s
133
+ end
134
+ end
135
+
136
+ endpoints << Grape::Endpoint.new(
137
+ in_setting,
138
+ method: :any,
139
+ path:,
140
+ app:,
141
+ route_options: { anchor: false },
142
+ forward_match: !app.respond_to?(:inheritable_setting),
143
+ for: self
144
+ )
145
+ end
146
+ end
147
+
148
+ # Defines a route that will be recognized
149
+ # by the Grape API.
150
+ #
151
+ # @param methods [HTTP Verb] One or more HTTP verbs that are accepted by this route. Set to `:any` if you want any verb to be accepted.
152
+ # @param paths [String] One or more strings representing the URL segment(s) for this route.
153
+ #
154
+ # @example Defining a basic route.
155
+ # class MyAPI < Grape::API
156
+ # route(:any, '/hello') do
157
+ # {hello: 'world'}
158
+ # end
159
+ # end
160
+ def route(methods, paths = ['/'], route_options = {}, &)
161
+ method = methods == :any ? '*' : methods
162
+ endpoint_params = inheritable_setting.namespace_stackable_with_hash(:params) || {}
163
+ endpoint_description = inheritable_setting.route[:description]
164
+ all_route_options = { params: endpoint_params }
165
+ all_route_options.deep_merge!(endpoint_description) if endpoint_description
166
+ all_route_options.deep_merge!(route_options) if route_options&.any?
167
+
168
+ new_endpoint = Grape::Endpoint.new(
169
+ inheritable_setting,
170
+ method:,
171
+ path: paths,
172
+ for: self,
173
+ route_options: all_route_options,
174
+ &
175
+ )
176
+ endpoints << new_endpoint unless endpoints.include?(new_endpoint)
177
+
178
+ inheritable_setting.route_end
179
+ reset_validations!
180
+ end
181
+
182
+ Grape::HTTP_SUPPORTED_METHODS.each do |supported_method|
183
+ define_method supported_method.downcase do |*args, **options, &block|
184
+ paths = args.first || ['/']
185
+ route(supported_method, paths, options, &block)
186
+ end
187
+ end
188
+
189
+ # Declare a "namespace", which prefixes all subordinate routes with its
190
+ # name. Any endpoints within a namespace, group, resource or segment,
191
+ # etc., will share their parent context as well as any configuration
192
+ # done in the namespace context.
193
+ #
194
+ # @example
195
+ #
196
+ # namespace :foo do
197
+ # get 'bar' do
198
+ # # defines the endpoint: GET /foo/bar
199
+ # end
200
+ # end
201
+ def namespace(space = nil, requirements: nil, **options, &block)
202
+ return Namespace.joined_space_path(inheritable_setting.namespace_stackable[:namespace]) unless space || block
203
+
204
+ within_namespace do
205
+ nest(block) do
206
+ inheritable_setting.namespace_stackable[:namespace] = Grape::Namespace.new(space, requirements:, **options) if space
207
+ end
208
+ end
209
+ end
210
+
211
+ alias group namespace
212
+ alias resource namespace
213
+ alias resources namespace
214
+ alias segment namespace
215
+
216
+ # An array of API routes.
217
+ def routes
218
+ @routes ||= endpoints.map(&:routes).flatten
219
+ end
220
+
221
+ # This method allows you to quickly define a parameter route segment
222
+ # in your API.
223
+ #
224
+ # @param param [Symbol] The name of the parameter you wish to declare.
225
+ # @option options [Regexp] You may supply a regular expression that the declared parameter must meet.
226
+ def route_param(param, requirements: nil, type: nil, **, &)
227
+ requirements = { param.to_sym => requirements } if requirements.is_a?(Regexp)
228
+
229
+ Grape::Validations::ParamsScope.new(api: self) do
230
+ requires param, type: type
231
+ end if type
232
+
233
+ namespace(":#{param}", requirements:, **, &)
234
+ end
235
+
236
+ # @return array of defined versions
237
+ def versions
238
+ @versions ||= []
239
+ end
240
+
241
+ private
242
+
243
+ # Remove all defined routes.
244
+ def reset_routes!
245
+ endpoints.each(&:reset_routes!)
246
+ @routes = nil
247
+ end
248
+
249
+ def reset_endpoints!
250
+ @endpoints = []
251
+ end
252
+
253
+ def refresh_mounted_api(mounts, *opts)
254
+ opts << { refresh_already_mounted: true }
255
+ mount(mounts, *opts)
256
+ end
257
+
258
+ # Execute first the provided block, then each of the
259
+ # block passed in. Allows for simple 'before' setups
260
+ # of settings stack pushes.
261
+ def nest(*blocks, &block)
262
+ blocks.compact!
263
+ if blocks.any?
264
+ evaluate_as_instance_with_configuration(block) if block
265
+ blocks.each { |b| evaluate_as_instance_with_configuration(b) }
266
+ reset_validations!
267
+ else
268
+ instance_eval(&block)
269
+ end
270
+ end
271
+
272
+ def evaluate_as_instance_with_configuration(block, lazy: false)
273
+ lazy_block = Grape::Util::Lazy::Block.new do |configuration|
274
+ value_for_configuration = configuration
275
+ self.configuration = value_for_configuration.evaluate if value_for_configuration.respond_to?(:lazy?) && value_for_configuration.lazy?
276
+ response = instance_eval(&block)
277
+ self.configuration = value_for_configuration
278
+ response
279
+ end
280
+ if @base && base_instance? && lazy
281
+ lazy_block
282
+ else
283
+ lazy_block.evaluate_from(configuration)
284
+ end
285
+ end
286
+ end
287
+ end
288
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module DSL
5
+ # Keeps track of settings (implemented as key-value pairs, grouped by
6
+ # types), in two contexts: top-level settings which apply globally no
7
+ # matter where they're defined, and inheritable settings which apply only
8
+ # in the current scope and scopes nested under it.
9
+ module Settings
10
+ attr_writer :inheritable_setting
11
+
12
+ # Fetch our top-level settings, which apply to all endpoints in the API.
13
+ def top_level_setting
14
+ @top_level_setting ||= Grape::Util::InheritableSetting.new.tap do |setting|
15
+ # Doesn't try to inherit settings from +Grape::API::Instance+ which also responds to
16
+ # +inheritable_setting+, however, it doesn't contain any user-defined settings.
17
+ # Otherwise, it would lead to an extra instance of +Grape::Util::InheritableSetting+
18
+ # in the chain for every endpoint.
19
+ setting.inherit_from superclass.inheritable_setting if defined?(superclass) && superclass.respond_to?(:inheritable_setting) && superclass != Grape::API::Instance
20
+ end
21
+ end
22
+
23
+ # Fetch our current inheritable settings, which are inherited by
24
+ # nested scopes but not shared across siblings.
25
+ def inheritable_setting
26
+ @inheritable_setting ||= Grape::Util::InheritableSetting.new.tap { |new_settings| new_settings.inherit_from top_level_setting }
27
+ end
28
+
29
+ def global_setting(key, value = nil)
30
+ get_or_set(inheritable_setting.global, key, value)
31
+ end
32
+
33
+ def route_setting(key, value = nil)
34
+ get_or_set(inheritable_setting.route, key, value)
35
+ end
36
+
37
+ def namespace_setting(key, value = nil)
38
+ get_or_set(inheritable_setting.namespace, key, value)
39
+ end
40
+
41
+ private
42
+
43
+ # Execute the block within a context where our inheritable settings are forked
44
+ # to a new copy (see #namespace_start).
45
+ def within_namespace
46
+ new_inheritable_settings = Grape::Util::InheritableSetting.new
47
+ new_inheritable_settings.inherit_from inheritable_setting
48
+
49
+ @inheritable_setting = new_inheritable_settings
50
+
51
+ result = yield
52
+
53
+ inheritable_setting.route_end
54
+ @inheritable_setting = inheritable_setting.parent
55
+ reset_validations!
56
+
57
+ result
58
+ end
59
+
60
+ def get_or_set(setting, key, value)
61
+ return setting[key] if value.nil?
62
+
63
+ setting[key] = value
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module DSL
5
+ module Validations
6
+ # Opens a root-level ParamsScope, defining parameter coercions and
7
+ # validations for the endpoint.
8
+ # @yield instance context of the new scope
9
+ def params(&)
10
+ Grape::Validations::ParamsScope.new(api: self, type: Hash, &)
11
+ end
12
+
13
+ # Declare the contract to be used for the endpoint's parameters.
14
+ # @param contract [Class<Dry::Validation::Contract> | Dry::Schema::Processor]
15
+ # The contract or schema to be used for validation. Optional.
16
+ # @yield a block yielding a new instance of Dry::Schema::Params
17
+ # subclass, allowing to define the schema inline. When the
18
+ # +contract+ parameter is a schema, it will be used as a parent. Optional.
19
+ def contract(contract = nil, &block)
20
+ raise ArgumentError, 'Either contract or block must be provided' unless contract || block
21
+ raise ArgumentError, 'Cannot inherit from contract, only schema' if block && contract.respond_to?(:schema)
22
+
23
+ Grape::Validations::ContractScope.new(self, contract, &block)
24
+ end
25
+
26
+ private
27
+
28
+ # Clears all defined parameters and validations. The main purpose of it is to clean up
29
+ # settings, so next endpoint won't interfere with previous one.
30
+ #
31
+ # params do
32
+ # # params for the endpoint below this block
33
+ # end
34
+ # post '/current' do
35
+ # # whatever
36
+ # end
37
+ #
38
+ # # somewhere between them the reset_validations! method gets called
39
+ #
40
+ # params do
41
+ # # params for the endpoint below this block
42
+ # end
43
+ # post '/next' do
44
+ # # whatever
45
+ # end
46
+ def reset_validations!
47
+ inheritable_setting.namespace_stackable.delete(:declared_params, :params, :validations)
48
+ end
49
+ end
50
+ end
51
+ end