Class: SafeType::Rule
- Inherits:
-
Object
- Object
- SafeType::Rule
- Defined in:
- lib/safe_type.rb
Instance Attribute Summary collapse
-
#after ⇒ Object
readonly
Returns the value of attribute after.
-
#before ⇒ Object
readonly
Returns the value of attribute before.
-
#default ⇒ Object
readonly
Returns the value of attribute default.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
-
#validate ⇒ Object
readonly
Returns the value of attribute validate.
Instance Method Summary collapse
- #apply(input) ⇒ Object
- #has_default? ⇒ Boolean
-
#initialize(r) ⇒ Rule
constructor
A new instance of Rule.
- #required? ⇒ Boolean
Constructor Details
#initialize(r) ⇒ Rule
Returns a new instance of Rule.
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/safe_type.rb', line 83 def initialize(r) raise ArgumentError, "SafeType::Rule has to be descried as a hash" \ unless r.class == ::Hash raise ArgumentError, ":type key is required" \ unless r.has_key?(:type) raise ArgumentError, ":type has to a class or module" \ unless r[:type].class == ::Class || r[:type].class == ::Module @type = r[:type] @required = false @required = true if r.has_key?(:required) && r[:required] @has_default = r.has_key?(:default) @default = r[:default] @before = r[:before] @after = r[:after] @validate = r[:validate] end |
Instance Attribute Details
#after ⇒ Object (readonly)
Returns the value of attribute after.
82 83 84 |
# File 'lib/safe_type.rb', line 82 def after @after end |
#before ⇒ Object (readonly)
Returns the value of attribute before.
82 83 84 |
# File 'lib/safe_type.rb', line 82 def before @before end |
#default ⇒ Object (readonly)
Returns the value of attribute default.
82 83 84 |
# File 'lib/safe_type.rb', line 82 def default @default end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
82 83 84 |
# File 'lib/safe_type.rb', line 82 def type @type end |
#validate ⇒ Object (readonly)
Returns the value of attribute validate.
82 83 84 |
# File 'lib/safe_type.rb', line 82 def validate @validate end |
Instance Method Details
#apply(input) ⇒ Object
104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/safe_type.rb', line 104 def apply(input) input = @before[input] unless @before.nil? begin result = Converter.to_type(input, @type) \ if @validate.nil? || (!@validate.nil? && @validate[input]) rescue return @default if @has_default return nil unless @required end result = @after[result] unless @after.nil? raise CoercionError if result.nil? && @required return @default if result.nil? result end |