Module: LuckyParam
- Defined in:
- lib/lucky_param.rb,
lib/lucky_param/checker.rb,
lib/lucky_param/version.rb
Defined Under Namespace
Classes: ParamFormatError, ParamMissError
Constant Summary
collapse
- CHECKER =
{
NONE: [
->(_obj) { true }
],
String: [
->(obj) { obj =~ /\w/ },
"must be valid String"
],
Integer: [
->(obj) { obj =~ /\d+/ },
"must be valid Integer"
],
Email: [
->(obj) { obj =~ /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/ },
"must be valid Email"
],
Float: [
->(obj) { obj =~ /^(-?\d+)(\.\d+)?$/ },
"must be valid Float"
],
Timestamp: [
->(obj) { obj =~ /^(\+|\-)?\d+$/ },
"must be valid Timestamp"
],
ArrayJSON: [
lambda { |obj|
begin
JSON.parse(obj).is_a?(Array)
rescue StandardError
false
end
},
"must be valid Array JSON"
],
HashJSON: [
lambda { |obj|
begin
JSON.parse(obj).is_a?(Hash)
rescue StandardError
false
end
},
"must be valid Hash JSON"
]
}.freeze
- VERSION =
"0.1.0".freeze
Instance Method Summary
collapse
Instance Method Details
#_checker_message(column, checker_type) ⇒ Object
33
34
35
36
37
38
39
40
|
# File 'lib/lucky_param.rb', line 33
def _checker_message(column, checker_type)
checker = CUSTOM_CHECKER[checker_type] if LuckyParam.const_defined?(:CUSTOM_CHECKER)
checker ||= CHECKER.fetch(checker_type) {
raise "Unknown checker `#{checker_type}`, try to define checker with const `LuckyParam::CUSTOM_CHECKER`"
}
result = checker[0].call(params[column])
result ? nil : checker[1]
end
|
#optional(column, checker_type = :NONE) ⇒ Object
26
27
28
29
30
31
|
# File 'lib/lucky_param.rb', line 26
def optional(column, checker_type = :NONE)
return unless params.key?(column)
message = _checker_message(column, checker_type)
raise ParamFormatError, message if message
end
|
#required(column, checker_type = :NONE) ⇒ Object
19
20
21
22
23
24
|
# File 'lib/lucky_param.rb', line 19
def required(column, checker_type = :NONE)
raise ParamMissError, column unless params.key?(column)
message = _checker_message(column, checker_type)
raise ParamFormatError, message if message
end
|