Class: Hanami::Action::Params

Inherits:
Object
  • Object
show all
Defined in:
lib/hanami/action/params.rb

Overview

A set of params requested by the client

It’s able to extract the relevant params from a Rack env of from an Hash.

There are three scenarios:

* When used with Hanami::Router: it contains only the params from the request
* When used standalone: it contains all the Rack env
* Default: it returns the given hash as it is. It's useful for testing purposes.

Since:

  • 0.1.0

Defined Under Namespace

Classes: DefaultContract, Errors

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env:, contract: nil) ⇒ Params

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize the params and freeze them.

Parameters:

  • env (Hash)

    a Rack env or an hash of params.

Since:

  • 0.1.0



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/hanami/action/params.rb', line 197

def initialize(env:, contract: nil)
  @env = env
  @raw = _extract_params

  # Fall back to the default contract here, rather than in the `._contract` method itself.
  # This allows `._contract` to return nil when there is no user-defined contract, which is
  # important for the backwards compatibility behavior in `Validatable::ClassMethods#params`.
  contract ||= self.class._contract || DefaultContract
  validation = contract.call(raw)

  @params = validation.to_h
  @errors = Errors.new(validation.errors.to_h)

  freeze
end

Class Attribute Details

._contractObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 2.2.0



157
158
159
# File 'lib/hanami/action/params.rb', line 157

def _contract
  @_contract
end

Instance Attribute Details

#envObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 0.7.0



164
165
166
# File 'lib/hanami/action/params.rb', line 164

def env
  @env
end

#errorsHash (readonly)

Returns structured error messages

Examples:

params.errors
  # => {
         :email=>["is missing", "is in invalid format"],
         :name=>["is missing"],
         :tos=>["is missing"],
         :age=>["is missing"],
         :address=>["is missing"]
       }

Returns:

  • (Hash)

Since:

  • 0.7.0



187
188
189
# File 'lib/hanami/action/params.rb', line 187

def errors
  @errors
end

#rawObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 0.7.0



170
171
172
# File 'lib/hanami/action/params.rb', line 170

def raw
  @raw
end

Class Method Details

.params(&block) ⇒ Object

Defines validations for the params, using the ‘params` schema of a dry-validation contract.

Parameters:

  • block (Proc)

    the schema definition

See Also:

Since:

  • 0.7.0



145
146
147
148
149
150
151
152
# File 'lib/hanami/action/params.rb', line 145

def self.params(&block)
  unless defined?(Dry::Validation::Contract)
    message = %(To use `.params`, please add the "hanami-validations" gem to your Gemfile)
    raise NoMethodError, message
  end

  @_contract = Class.new(Dry::Validation::Contract) { params(&block || -> {}) }.new
end

Instance Method Details

#[](key) ⇒ Object?

Returns the value for the given params key.

Parameters:

  • key (Symbol)

    the key

Returns:

  • (Object, nil)

    the associated value, if found

Since:

  • 0.7.0



221
222
223
# File 'lib/hanami/action/params.rb', line 221

def [](key)
  @params[key]
end

#deconstruct_keys::Hash

Pattern-matching support

Returns:

  • (::Hash)

Since:

  • 2.0.2



340
341
342
# File 'lib/hanami/action/params.rb', line 340

def deconstruct_keys(*)
  to_hash
end

#each {|key, value| ... } ⇒ to_h

Iterates over the params.

Calls the given block with each param key-value pair; returns the full hash of params.

Yield Parameters:

  • key (Symbol)
  • value (Object)

Returns:

Since:

  • 0.7.1



321
322
323
# File 'lib/hanami/action/params.rb', line 321

def each(&blk)
  to_h.each(&blk)
end

#error_messages(error_set = errors) ⇒ Array

Returns flat collection of full error messages

Examples:

params.error_messages
  # => [
         "Email is missing",
         "Email is in invalid format",
         "Name is missing",
         "Tos is missing",
         "Age is missing",
         "Address is missing"
       ]

Returns:

  • (Array)

Since:

  • 0.7.0



283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/hanami/action/params.rb', line 283

def error_messages(error_set = errors)
  error_set.each_with_object([]) do |(key, messages), result|
    k = Utils::String.titleize(key)

    msgs = if messages.is_a?(::Hash)
             error_messages(messages)
           else
             messages.map { |message| "#{k} #{message}" }
           end

    result.concat(msgs)
  end
end

#get(*keys) ⇒ Object, NilClass Also known as: dig

Returns an value associated with the given params key.

You can access nested attributes by listing all the keys in the path. This uses the same key path semantics as ‘Hash#dig`.

Examples:

require "hanami/controller"

module Deliveries
  class Create < Hanami::Action
    def handle(req, *)
      req.params.get(:customer_name)     # => "Luca"
      req.params.get(:uknown)            # => nil

      req.params.get(:address, :city)    # => "Rome"
      req.params.get(:address, :unknown) # => nil

      req.params.get(:tags, 0)           # => "foo"
      req.params.get(:tags, 1)           # => "bar"
      req.params.get(:tags, 999)         # => nil

      req.params.get(nil)                # => nil
    end
  end
end

Parameters:

  • keys (Array<Symbol,Integer>)

    the key

Returns:

  • (Object, NilClass)

    return the associated value, if found

Since:

  • 0.7.0



257
258
259
# File 'lib/hanami/action/params.rb', line 257

def get(*keys)
  @params.dig(*keys)
end

#to_h::Hash Also known as: to_hash

Serialize validated params to Hash

Returns:

  • (::Hash)

Since:

  • 0.3.0



330
331
332
# File 'lib/hanami/action/params.rb', line 330

def to_h
  @params
end

#valid?TrueClass, FalseClass

Returns true if no validation errors are found, false otherwise.

Examples:

params.valid? # => true

Returns:

  • (TrueClass, FalseClass)

Since:

  • 0.7.0



306
307
308
# File 'lib/hanami/action/params.rb', line 306

def valid?
  errors.empty?
end