Class: SafeType::Rule
- Inherits:
-
Object
- Object
- SafeType::Rule
- Defined in:
- lib/safe_type/rule.rb
Class Method Summary collapse
Instance Method Summary collapse
- #after(input) ⇒ Object
- #before(input) ⇒ Object
- #coerce(input, key = nil) ⇒ Object
-
#initialize(type:, default: nil, required: false, **args) ⇒ Rule
constructor
A new instance of Rule.
- #is_valid?(input) ⇒ Boolean
Constructor Details
#initialize(type:, default: nil, required: false, **args) ⇒ Rule
Returns a new instance of Rule.
6 7 8 9 10 11 12 13 |
# File 'lib/safe_type/rule.rb', line 6 def initialize(type:, default: nil, required: false, **args) unless type.class == ::Class || type.class == ::Module raise ArgumentError.new("type has to a class or module") end @type = type @required = required @default = default end |
Class Method Details
.coerce(input) ⇒ Object
27 28 29 |
# File 'lib/safe_type/rule.rb', line 27 def self.coerce(input) default.coerce(input) end |
.default ⇒ Object
31 32 33 |
# File 'lib/safe_type/rule.rb', line 31 def self.default new end |
.strict ⇒ Object
35 36 37 |
# File 'lib/safe_type/rule.rb', line 35 def self.strict new(required: true) end |
Instance Method Details
#after(input) ⇒ Object
23 24 25 |
# File 'lib/safe_type/rule.rb', line 23 def after(input) input end |
#before(input) ⇒ Object
19 20 21 |
# File 'lib/safe_type/rule.rb', line 19 def before(input) input end |
#coerce(input, key = nil) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/safe_type/rule.rb', line 39 def coerce(input, key=nil) raise SafeType::EmptyValueError.new(@type, key) if input.nil? && @required input = before(input) input = Converter.to_type(input, @type) raise SafeType::ValidationError.new(input, @type, key) unless is_valid?(input) result = after(input) raise SafeType::EmptyValueError.new(@type, key) if result.nil? && @required return @default if result.nil? raise SafeType::CoercionError.new(result, @type, key) unless result.is_a?(@type) result rescue TypeError, ArgumentError, NoMethodError return @default if input.nil? && !@required raise SafeType::CoercionError.new(input, @type, key) end |
#is_valid?(input) ⇒ Boolean
15 16 17 |
# File 'lib/safe_type/rule.rb', line 15 def is_valid?(input) true end |