Module: Locomotive::API::Helpers::ParamsHelper

Defined in:
app/api/locomotive/api/helpers/params_helper.rb

Instance Method Summary collapse

Instance Method Details

#build_uploaded_files_from_params!(hash, list) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'app/api/locomotive/api/helpers/params_helper.rb', line 36

def build_uploaded_files_from_params!(hash, list)
  list.each do |name|
    file_hash = hash[name]

    next unless file_hash.try(:has_key?, :tempfile)

    hash[name] = ActionDispatch::Http::UploadedFile.new(file_hash)
  end
end

#json_params!(hash, keys) ⇒ Object



46
47
48
49
50
# File 'app/api/locomotive/api/helpers/params_helper.rb', line 46

def json_params!(hash, keys)
  {}.tap do |json_params|
    keys.each { |key| json_params[key] = hash.delete(key) }
  end
end

#permitted_paramsObject



6
7
8
# File 'app/api/locomotive/api/helpers/params_helper.rb', line 6

def permitted_params
  @permitted_params ||= declared(params, include_missing: false)
end

#permitted_params_from_policy(object_or_class, key, file_keys = nil, json_keys = nil) ⇒ Object

Much safer than permitted_params because it also uses the current policy (Pundit) to filter the parameters.

Examples:

permitted_params_from_policy(current_site, :site)

If we want to deal with ActionDispatch::Http::UploadedFile instances instead of hashes (which would break the permitted attributes policy).

permitted_params_from_policy(current_site, :site, [:picture])



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'app/api/locomotive/api/helpers/params_helper.rb', line 22

def permitted_params_from_policy(object_or_class, key, file_keys = nil, json_keys = nil)
  _params = permitted_params[key]

  build_uploaded_files_from_params!(_params, file_keys) if file_keys

  json_params = json_params!(_params, json_keys || [])

  _attributes = policy(object_or_class).permitted_attributes

  ::ActionController::Parameters.new(_params).permit(*_attributes).tap do |strong_params|
    (json_keys || []).each { |k| strong_params[k] = json_params[k] }
  end
end