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,198 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ # Module for code related to grape's system for
6
+ # coercion and type validation of incoming request
7
+ # parameters.
8
+ #
9
+ # Grape uses a number of tests and assertions to
10
+ # work out exactly how a parameter should be handled,
11
+ # based on the +type+ and +coerce_with+ options that
12
+ # may be supplied to {Grape::Dsl::Parameters#requires}
13
+ # and {Grape::Dsl::Parameters#optional}. The main
14
+ # entry point for this process is {Types.build_coercer}.
15
+ module Types
16
+ module_function
17
+
18
+ PRIMITIVES = [
19
+ # Numerical
20
+ Integer,
21
+ Float,
22
+ BigDecimal,
23
+ Numeric,
24
+
25
+ # Date/time
26
+ Date,
27
+ DateTime,
28
+ Time,
29
+
30
+ # Misc
31
+ Grape::API::Boolean,
32
+ String,
33
+ Symbol,
34
+ TrueClass,
35
+ FalseClass
36
+ ].freeze
37
+
38
+ # Types representing data structures.
39
+ STRUCTURES = [Hash, Array, Set].freeze
40
+
41
+ SPECIAL = {
42
+ ::JSON => Json,
43
+ Array[JSON] => JsonArray,
44
+ ::File => File,
45
+ Rack::Multipart::UploadedFile => File
46
+ }.freeze
47
+
48
+ GROUPS = [Array, Hash, JSON, Array[JSON]].freeze
49
+
50
+ # Is the given class a primitive type as recognized by Grape?
51
+ #
52
+ # @param type [Class] type to check
53
+ # @return [Boolean] whether or not the type is known by Grape as a valid
54
+ # type for a single value
55
+ def primitive?(type)
56
+ PRIMITIVES.include?(type)
57
+ end
58
+
59
+ # Is the given class a standard data structure (collection or map)
60
+ # as recognized by Grape?
61
+ #
62
+ # @param type [Class] type to check
63
+ # @return [Boolean] whether or not the type is known by Grape as a valid
64
+ # data structure type
65
+ def structure?(type)
66
+ STRUCTURES.include?(type)
67
+ end
68
+
69
+ # Is the declared type in fact an array of multiple allowed types?
70
+ # For example the declaration +types: [Integer,String]+ will attempt
71
+ # first to coerce given values to integer, but will also accept any
72
+ # other string.
73
+ #
74
+ # @param type [Array<Class>,Set<Class>] type (or type list!) to check
75
+ # @return [Boolean] +true+ if the given value will be treated as
76
+ # a list of types.
77
+ def multiple?(type)
78
+ (type.is_a?(Array) || type.is_a?(Set)) && type.size > 1
79
+ end
80
+
81
+ # Does Grape provide special coercion and validation
82
+ # routines for the given class? This does not include
83
+ # automatic handling for primitives, structures and
84
+ # otherwise recognized types. See {Types::SPECIAL}.
85
+ #
86
+ # @param type [Class] type to check
87
+ # @return [Boolean] +true+ if special routines are available
88
+ def special?(type)
89
+ SPECIAL.key? type
90
+ end
91
+
92
+ # Is the declared type a supported group type?
93
+ # Currently supported group types are Array, Hash, JSON, and Array[JSON]
94
+ #
95
+ # @param type [Array<Class>,Class] type to check
96
+ # @return [Boolean] +true+ if the type is a supported group type
97
+ def group?(type)
98
+ GROUPS.include? type
99
+ end
100
+
101
+ # A valid custom type must implement a class-level `parse` method, taking
102
+ # one String argument and returning the parsed value in its correct type.
103
+ #
104
+ # @param type [Class] type to check
105
+ # @return [Boolean] whether or not the type can be used as a custom type
106
+ def custom?(type)
107
+ !primitive?(type) &&
108
+ !structure?(type) &&
109
+ !multiple?(type) &&
110
+ type.respond_to?(:parse) &&
111
+ type.method(:parse).arity == 1
112
+ end
113
+
114
+ # Is the declared type an +Array+ or +Set+ of a {#custom?} type?
115
+ #
116
+ # @param type [Array<Class>,Class] type to check
117
+ # @return [Boolean] true if +type+ is a collection of a type that implements
118
+ # its own +#parse+ method.
119
+ def collection_of_custom?(type)
120
+ (type.is_a?(Array) || type.is_a?(Set)) &&
121
+ type.length == 1 &&
122
+ (custom?(type.first) || special?(type.first))
123
+ end
124
+
125
+ def map_special(type)
126
+ SPECIAL.fetch(type, type)
127
+ end
128
+
129
+ # Chooses the best coercer for the given type. For example, if the type
130
+ # is Integer, it will return a coercer which will be able to coerce a value
131
+ # to the integer.
132
+ #
133
+ # There are a few very special coercers which might be returned.
134
+ #
135
+ # +Grape::Types::MultipleTypeCoercer+ is a coercer which is returned when
136
+ # the given type implies values in an array with different types.
137
+ # For example, +[Integer, String]+ allows integer and string values in
138
+ # an array.
139
+ #
140
+ # +Grape::Types::CustomTypeCoercer+ is a coercer which is returned when
141
+ # a method is specified by a user with +coerce_with+ option or the user
142
+ # specifies a custom type which implements requirments of
143
+ # +Grape::Types::CustomTypeCoercer+.
144
+ #
145
+ # +Grape::Types::CustomTypeCollectionCoercer+ is a very similar to the
146
+ # previous one, but it expects an array or set of values having a custom
147
+ # type implemented by the user.
148
+ #
149
+ # There is also a group of custom types implemented by Grape, check
150
+ # +Grape::Validations::Types::SPECIAL+ to get the full list.
151
+ #
152
+ # @param type [Class] the type to which input strings
153
+ # should be coerced
154
+ # @param method [Class,#call] the coercion method to use
155
+ # @return [Object] object to be used
156
+ # for coercion and type validation
157
+ def build_coercer(type, method: nil, strict: false)
158
+ # no cache since unique
159
+ return create_coercer_instance(type, method, strict) if method.respond_to?(:call)
160
+
161
+ CoercerCache[[type, method, strict]]
162
+ end
163
+
164
+ def create_coercer_instance(type, method, strict)
165
+ # Maps a custom type provided by Grape, it doesn't map types wrapped by collections!!!
166
+ type = Types.map_special(type)
167
+
168
+ # Use a special coercer for multiply-typed parameters.
169
+ if Types.multiple?(type)
170
+ MultipleTypeCoercer.new(type, method)
171
+
172
+ # Use a special coercer for custom types and coercion methods.
173
+ elsif method || Types.custom?(type)
174
+ CustomTypeCoercer.new(type, method)
175
+
176
+ # Special coercer for collections of types that implement a parse method.
177
+ # CustomTypeCoercer (above) already handles such types when an explicit coercion
178
+ # method is supplied.
179
+ elsif Types.collection_of_custom?(type)
180
+ Types::CustomTypeCollectionCoercer.new(
181
+ Types.map_special(type.first), type.is_a?(Set)
182
+ )
183
+ else
184
+ DryTypeCoercer.coercer_instance_for(type, strict)
185
+ end
186
+ end
187
+
188
+ class CoercerCache < Grape::Util::Cache
189
+ def initialize
190
+ super
191
+ @cache = Hash.new do |h, (type, method, strict)|
192
+ h[[type, method, strict]] = Grape::Validations::Types.create_coercer_instance(type, method, strict)
193
+ end
194
+ end
195
+ end
196
+ end
197
+ end
198
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class AllOrNoneOfValidator < MultipleParamsBase
7
+ default_message_key :all_or_none
8
+
9
+ def validate_params!(params)
10
+ known_keys = all_keys
11
+ keys = keys_in_common(params, known_keys)
12
+ return if keys.empty? || keys.length == @attrs.length
13
+
14
+ validation_error!(known_keys)
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class AllowBlankValidator < Base
7
+ default_message_key :blank
8
+
9
+ def initialize(attrs, options, required, scope, opts)
10
+ super
11
+ @value = option_value
12
+ end
13
+
14
+ def validate_param!(attr_name, params)
15
+ return if @value || !hash_like?(params)
16
+
17
+ value = scrub(params[attr_name])
18
+ return if value == false || value.present?
19
+
20
+ validation_error!(attr_name)
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class AsValidator < Base
7
+ # We use a validator for renaming parameters. This is just a marker for
8
+ # the parameter scope to handle the renaming. No actual validation
9
+ # happens here.
10
+ def validate_param!(*); end
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class AtLeastOneOfValidator < MultipleParamsBase
7
+ default_message_key :at_least_one
8
+
9
+ def validate_params!(params)
10
+ known_keys = all_keys
11
+ return if hash_like?(params) && known_keys.intersect?(params.keys.map { |attr| @scope.full_name(attr) })
12
+
13
+ validation_error!(known_keys)
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,158 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ # Base class for all parameter validators.
7
+ #
8
+ # == Freeze contract
9
+ # Validator instances are shared across requests and are frozen after
10
+ # initialization (via +.new+). All inputs (+options+, +opts+, +attrs+)
11
+ # arrive pre-frozen from the DSL boundary, so subclass ivars derived
12
+ # from them are frozen by construction. Lazy ivar assignment
13
+ # (e.g. +memoize+, <tt>||=</tt>) will raise +FrozenError+ at request time.
14
+ class Base
15
+ include Grape::Util::Translation
16
+
17
+ attr_reader :attrs
18
+
19
+ class << self
20
+ # Declares the default I18n message key used by +validation_error!+.
21
+ # Subclasses that only need a single fixed error message can declare it
22
+ # at the class level instead of overriding +initialize+:
23
+ #
24
+ # class MyValidator < Grape::Validations::Validators::Base
25
+ # default_message_key :my_error
26
+ # end
27
+ #
28
+ # The key is resolved through +message+, so a per-option +:message+
29
+ # override still takes precedence.
30
+ def default_message_key(key = nil)
31
+ if key
32
+ @default_message_key = key
33
+ else
34
+ @default_message_key || (superclass.respond_to?(:default_message_key) ? superclass.default_message_key : nil)
35
+ end
36
+ end
37
+
38
+ def new(...)
39
+ super.freeze
40
+ end
41
+
42
+ def inherited(klass)
43
+ super
44
+ Validations.register(klass)
45
+ end
46
+ end
47
+
48
+ # Creates a new Validator from options specified
49
+ # by a +requires+ or +optional+ directive during
50
+ # parameter definition.
51
+ # @param attrs [Array] names of attributes to which the Validator applies
52
+ # @param options [Object] implementation-dependent Validator options; deep-frozen on assignment
53
+ # @param required [Boolean] attribute(s) are required or optional
54
+ # @param scope [ParamsScope] parent scope for this Validator
55
+ # @param opts [Hash] additional validation options
56
+ def initialize(attrs, options, required, scope, opts)
57
+ @attrs = Array(attrs).freeze
58
+ @options = Grape::Util::DeepFreeze.deep_freeze(options)
59
+ @option = @options # TODO: remove in next major release
60
+ @required = required
61
+ @scope = scope
62
+ @fail_fast, @allow_blank = opts.values_at(:fail_fast, :allow_blank)
63
+ @exception_message = message(self.class.default_message_key) if self.class.default_message_key
64
+ end
65
+
66
+ # Validates a given request.
67
+ # @note Override #validate! unless you need to access the entire request.
68
+ # @param request [Grape::Request] the request currently being handled
69
+ # @raise [Grape::Exceptions::Validation] if validation failed
70
+ # @return [void]
71
+ def validate(request)
72
+ return unless @scope.should_validate?(request.params)
73
+
74
+ validate!(request.params)
75
+ end
76
+
77
+ def fail_fast?
78
+ @fail_fast
79
+ end
80
+
81
+ # Validates a given parameter hash.
82
+ # @note Override #validate_param! for per-parameter validation,
83
+ # or #validate if you need access to the entire request.
84
+ # @param params [Hash] parameters to validate
85
+ # @raise [Grape::Exceptions::Validation] if validation failed
86
+ # @return [void]
87
+ def validate!(params)
88
+ attributes = SingleAttributeIterator.new(@attrs, @scope, params)
89
+ # we collect errors inside array because
90
+ # there may be more than one error per field
91
+ array_errors = []
92
+
93
+ attributes.each do |val, attr_name, empty_val|
94
+ next if !@scope.required? && empty_val
95
+ next unless @scope.meets_dependency?(val, params)
96
+
97
+ validate_param!(attr_name, val) if @required || (hash_like?(val) && val.key?(attr_name))
98
+ rescue Grape::Exceptions::Validation => e
99
+ array_errors << e
100
+ end
101
+
102
+ raise Grape::Exceptions::ValidationArrayErrors.new(array_errors) if array_errors.any?
103
+ end
104
+
105
+ protected
106
+
107
+ # Validates a single attribute. Override in subclasses.
108
+ # @param attr_name [Symbol, String] the attribute name
109
+ # @param params [Hash] the parameter hash containing the attribute
110
+ # @raise [Grape::Exceptions::Validation] if validation failed
111
+ # @return [void]
112
+ def validate_param!(attr_name, params)
113
+ raise NotImplementedError
114
+ end
115
+
116
+ private
117
+
118
+ def validation_error!(attr_name_or_params, message = @exception_message)
119
+ params = attr_name_or_params.is_a?(Array) ? attr_name_or_params : @scope.full_name(attr_name_or_params)
120
+ raise Grape::Exceptions::Validation.new(params:, message:)
121
+ end
122
+
123
+ def hash_like?(obj)
124
+ obj.respond_to?(:key?)
125
+ end
126
+
127
+ def options_key?(key, options = nil)
128
+ current_options = options || @options
129
+ hash_like?(current_options) && current_options.key?(key) && !current_options[key].nil?
130
+ end
131
+
132
+ # Returns the effective message for a validation error.
133
+ # Prefers an explicit +:message+ option, then +default_key+.
134
+ # If both are nil, the block (if given) is called to compute a fallback —
135
+ # useful for validators that build a message Hash for deferred i18n interpolation.
136
+ # @example
137
+ # @exception_message = message(:presence) # symbol key or custom message
138
+ # @exception_message = message { build_hash_message } # computed fallback
139
+ def message(default_key = nil)
140
+ key = options_key?(:message) ? @options[:message] : default_key
141
+ return key unless key.nil?
142
+
143
+ yield if block_given?
144
+ end
145
+
146
+ def option_value
147
+ options_key?(:value) ? @options[:value] : @options
148
+ end
149
+
150
+ def scrub(value)
151
+ return value unless value.respond_to?(:valid_encoding?) && !value.valid_encoding?
152
+
153
+ value.scrub
154
+ end
155
+ end
156
+ end
157
+ end
158
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class CoerceValidator < Base
7
+ default_message_key :coerce
8
+
9
+ def initialize(attrs, options, required, scope, opts)
10
+ super
11
+
12
+ raw_type = @options[:type]
13
+ type = hash_like?(raw_type) ? raw_type[:value] : raw_type
14
+ @converter =
15
+ if type.is_a?(Grape::Validations::Types::VariantCollectionCoercer)
16
+ type
17
+ else
18
+ Types.build_coercer(type, method: @options[:method])
19
+ end
20
+ end
21
+
22
+ def validate_param!(attr_name, params)
23
+ validation_error!(attr_name) unless hash_like?(params)
24
+
25
+ new_value = coerce_value(params[attr_name])
26
+
27
+ validation_error!(attr_name, new_value.message || @exception_message) if new_value.is_a?(Types::InvalidValue)
28
+
29
+ # Don't assign a value if it is identical. It fixes a problem with Hashie::Mash
30
+ # which looses wrappers for hashes and arrays after reassigning values
31
+ #
32
+ # h = Hashie::Mash.new(list: [1, 2, 3, 4])
33
+ # => #<Hashie::Mash list=#<Hashie::Array [1, 2, 3, 4]>>
34
+ # list = h.list
35
+ # h[:list] = list
36
+ # h
37
+ # => #<Hashie::Mash list=[1, 2, 3, 4]>
38
+ return if params[attr_name].instance_of?(new_value.class) && params[attr_name] == new_value
39
+
40
+ params[attr_name] = new_value
41
+ end
42
+
43
+ private
44
+
45
+ # Calls the converter built at definition time.
46
+ # Custom coercers may raise; any StandardError is treated as an invalid value.
47
+ def coerce_value(val)
48
+ @converter.call(val)
49
+ rescue StandardError
50
+ Types::InvalidValue.new
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class ContractScopeValidator
7
+ attr_reader :schema
8
+
9
+ def initialize(schema:)
10
+ @schema = schema
11
+ freeze
12
+ end
13
+
14
+ # Validates a given request.
15
+ # @param request [Grape::Request] the request currently being handled
16
+ # @raise [Grape::Exceptions::ValidationArrayErrors] if validation failed
17
+ # @return [void]
18
+ def validate(request)
19
+ res = schema.call(request.params)
20
+
21
+ if res.success?
22
+ request.params.deep_merge!(res.to_h)
23
+ return
24
+ end
25
+
26
+ raise Grape::Exceptions::ValidationArrayErrors.new(build_errors_from_messages(res.errors.messages))
27
+ end
28
+
29
+ def fail_fast?
30
+ false
31
+ end
32
+
33
+ private
34
+
35
+ def build_errors_from_messages(messages)
36
+ messages.map do |message|
37
+ full_name = message.path.first.to_s
38
+ full_name << "[#{message.path[1..].join('][')}]" if message.path.size > 1
39
+ Grape::Exceptions::Validation.new(params: full_name, message: message.text)
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class DefaultValidator < Base
7
+ def initialize(attrs, options, required, scope, opts)
8
+ super
9
+ # !important, lazy call at runtime
10
+ @default_call =
11
+ if @options.is_a?(Proc)
12
+ @options.arity.zero? ? proc { @options.call } : @options
13
+ elsif @options.duplicable?
14
+ proc { @options.dup }
15
+ else
16
+ proc { @options }
17
+ end
18
+ end
19
+
20
+ def validate!(params)
21
+ attrs = SingleAttributeIterator.new(@attrs, @scope, params)
22
+ attrs.each do |resource_params, attr_name|
23
+ next unless @scope.meets_dependency?(resource_params, params)
24
+
25
+ resource_params[attr_name] = @default_call.call(resource_params) if hash_like?(resource_params) && resource_params[attr_name].nil?
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class ExactlyOneOfValidator < MultipleParamsBase
7
+ def initialize(attrs, options, required, scope, opts)
8
+ super
9
+ @exactly_one_exception_message = message(:exactly_one)
10
+ @mutual_exclusion_exception_message = message(:mutual_exclusion)
11
+ end
12
+
13
+ def validate_params!(params)
14
+ known_keys = all_keys
15
+ keys = keys_in_common(params, known_keys)
16
+ return if keys.length == 1
17
+
18
+ validation_error!(known_keys, @exactly_one_exception_message) if keys.empty?
19
+ validation_error!(keys, @mutual_exclusion_exception_message)
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class ExceptValuesValidator < Base
7
+ default_message_key :except_values
8
+
9
+ def initialize(attrs, options, required, scope, opts)
10
+ super
11
+ except = option_value
12
+ raise ArgumentError, 'except_values Proc must have arity of zero (use values: with a one-arity predicate for per-element checks)' if except.is_a?(Proc) && !except.arity.zero?
13
+
14
+ # Zero-arity procs (e.g. -> { User.pluck(:role) }) must be called per-request,
15
+ # not at definition time, so they are wrapped in a lambda to defer execution.
16
+ @excepts_call = except.is_a?(Proc) ? except : -> { except }
17
+ end
18
+
19
+ def validate_param!(attr_name, params)
20
+ return unless hash_like?(params) && params.key?(attr_name)
21
+
22
+ excepts = @excepts_call.call
23
+ return if excepts.nil?
24
+
25
+ param_array = params[attr_name].nil? ? [nil] : Array.wrap(params[attr_name])
26
+ return if param_array.none? { |param| excepts.include?(param) }
27
+
28
+ validation_error!(attr_name)
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Grape
4
+ module Validations
5
+ module Validators
6
+ class LengthValidator < Base
7
+ def initialize(attrs, options, required, scope, opts)
8
+ super
9
+
10
+ @min, @max, @is = @options.values_at(:min, :max, :is)
11
+ validate_boundary!(:min, @min)
12
+ validate_boundary!(:max, @max)
13
+ raise ArgumentError, "min #{@min} cannot be greater than max #{@max}" if @min && @max && @min > @max
14
+
15
+ return if @is.nil?
16
+ raise ArgumentError, 'is must be an integer greater than zero' unless @is.is_a?(Integer) && @is.positive?
17
+ raise ArgumentError, 'is cannot be combined with min or max' unless @min.nil? && @max.nil?
18
+ end
19
+
20
+ def validate_param!(attr_name, params)
21
+ param = params[attr_name]
22
+
23
+ return unless param.respond_to?(:length)
24
+
25
+ return unless (!@min.nil? && param.length < @min) || (!@max.nil? && param.length > @max) || (!@is.nil? && param.length != @is)
26
+
27
+ validation_error!(attr_name, message do
28
+ if @min && @max
29
+ translate(:length, min: @min, max: @max)
30
+ elsif @min
31
+ translate(:length_min, min: @min)
32
+ elsif @max
33
+ translate(:length_max, max: @max)
34
+ else
35
+ translate(:length_is, is: @is)
36
+ end
37
+ end)
38
+ end
39
+
40
+ private
41
+
42
+ def validate_boundary!(name, val)
43
+ raise ArgumentError, "#{name} must be an integer greater than or equal to zero" if !val.nil? && (!val.is_a?(Integer) || val.negative?)
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end