Module: StrongerParameters::Parameters

Extended by:
ActiveSupport::Concern
Defined in:
lib/stronger_parameters/parameters.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#hash_filter_with_stronger_parameters(params, filter) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/stronger_parameters/parameters.rb', line 128

def hash_filter_with_stronger_parameters(params, filter)
  stronger_filter = ActiveSupport::HashWithIndifferentAccess.new
  other_filter    = ActiveSupport::HashWithIndifferentAccess.new

  filter.each do |k, v|
    if v.is_a?(Constraint)
      stronger_filter[k] = v
    else
      other_filter[k] = v
    end
  end

  hash_filter_without_stronger_parameters(params, other_filter)

  stronger_filter.keys.each do |key|
    value = fetch(key, nil)
    result = nil

    if value.nil? && self.class.allow_nil_for_everything
      params[key] = nil if key?(key)
      next
    end

    constraint = stronger_filter[key]

    if key?(key)
      result = constraint.value(value)
    elsif constraint.required?
      result = InvalidValue.new(nil, 'must be present')
    else
      next
    end

    if result.is_a?(InvalidValue)
      name = "invalid_parameter.action_controller"
      ActiveSupport::Notifications.publish(name, key: key, value: value, message: result.message)

      action = self.class.action_on_invalid_parameters
      case action
      when :raise, nil
        raise StrongerParameters::InvalidParameter.new(result, key)
      when Proc
        action.call(result, key)
      when :log
        Rails.logger.warn("#{key} #{result.message}, but was: #{value.inspect}")
      else
        raise ArgumentError, "Unsupported value in action_on_invalid_parameters: #{action}"
      end

      params[key] = value
    else
      params[key] = result
    end
  end
end