Method: Grape::Endpoint#declared

Defined in:
lib/grape/endpoint.rb

#declared(params, options = {}, declared_params = ) ⇒ Object

A filtering method that will return a hash consisting only of keys that have been declared by a params statement.

Parameters:

  • params (Hash)

    The initial hash to filter. Usually this will just be params

  • options (Hash) (defaults to: {})

    Can pass :include_missing and :stringify options.



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/grape/endpoint.rb', line 171

def declared(params, options = {}, declared_params = settings[:declared_params])
  options[:include_missing] = true unless options.key?(:include_missing)

  unless declared_params
    raise ArgumentError, "Tried to filter for declared parameters but none exist."
  end

  if params.is_a? Array
    params.map do |param|
      declared(param || {}, options, declared_params)
    end
  else
    declared_params.inject({}) do |hash, key|
      key = { key => nil } unless key.is_a? Hash

      key.each_pair do |parent, children|
        output_key = options[:stringify] ? parent.to_s : parent.to_sym
        if params.key?(parent) || options[:include_missing]
          hash[output_key] = if children
                               declared(params[parent] || {}, options, Array(children))
                             else
                               params[parent]
                             end
        end
      end

      hash
    end
  end
end