/
params.rb
123 lines (110 loc) · 2.92 KB
/
params.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
require 'hanami/action/base_params'
require 'hanami/validations/form'
module Hanami
module Action
# 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
class Params < BaseParams
include Hanami::Validations::Form
# This is a Hanami::Validations extension point
#
# @since 0.7.0
# @api private
def self._base_rules
lambda do
optional(:_csrf_token).filled(:str?)
end
end
def self.params(&blk)
validations(&blk || ->() {})
end
# Initialize the params and freeze them.
#
# @param env [Hash] a Rack env or an hash of params.
#
# @return [Params]
#
# @since 0.1.0
def initialize(env)
@env = env
super(_extract_params)
@result = validate
@params = _params
freeze
end
# Returns raw params from Rack env
#
# @return [Hash]
#
# @since 0.3.2
def raw
@input
end
# Returns structured error messages
#
# @return [Hash]
#
# @since 0.7.0
#
# @example
# params.errors
# # => {:email=>["is missing", "is in invalid format"], :name=>["is missing"], :tos=>["is missing"], :age=>["is missing"], :address=>["is missing"]}
def errors
@result.messages
end
# Returns flat collection of full error messages
#
# @return [Array]
#
# @since 0.7.0
#
# @example
# params.error_messages
# # => ["Email is missing", "Email is in invalid format", "Name is missing", "Tos is missing", "Age is missing", "Address is missing"]
def error_messages(error_set = errors)
error_set.each_with_object([]) do |(key, messages), result|
k = Utils::String.new(key).titleize
_messages = if messages.is_a?(Hash)
error_messages(messages)
else
messages.map { |message| "#{k} #{message}" }
end
result.concat(_messages)
end
end
# Returns true if no validation errors are found,
# false otherwise.
#
# @return [TrueClass, FalseClass]
#
# @since 0.7.0
#
# @example
# params.valid? # => true
def valid?
@result.success?
end
# Serialize params to Hash
#
# @return [::Hash]
#
# @since 0.3.0
def to_h
@params
end
alias_method :to_hash, :to_h
private
def _params
@result.output.merge(_router_params)
end
end
end
end