Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/hoodie/core_ext/try.rb,
lib/hoodie/core_ext/blank.rb
Overview
Add #blank? and #present? methods to Object class.
Instance Method Summary collapse
-
#blank? ⇒ TrueClass, FalseClass
Returns true if the object is nil or empty (if applicable).
-
#present? ⇒ TrueClass, FalseClass
Returns true if the object is NOT nil or empty.
-
#try(*a, &b) ⇒ Object
Invokes the public method whose name goes as first argument just like ‘public_send` does, except that if the receiver does not respond to it the call returns `nil` rather than raising an exception.
-
#try!(*a, &b) ⇒ Object
Same as #try, but will raise a NoMethodError exception if the receiver is not ‘nil` and does not implement the tried method.
Instance Method Details
#blank? ⇒ TrueClass, FalseClass
Returns true if the object is nil or empty (if applicable)
[].blank? #=> true
[1].blank? #=> false
[nil].blank? #=> false
30 31 32 |
# File 'lib/hoodie/core_ext/blank.rb', line 30 def blank? nil? || (respond_to?(:empty?) && empty?) end |
#present? ⇒ TrueClass, FalseClass
Returns true if the object is NOT nil or empty
[].present? #=> false
[1].present? #=> true
[nil].present? #=> true
42 43 44 |
# File 'lib/hoodie/core_ext/blank.rb', line 42 def present? !blank? end |
#try(*a, &b) ⇒ Object
‘try` is defined on `Object`. Therefore, it won’t work with instances
Invokes the public method whose name goes as first argument just like ‘public_send` does, except that if the receiver does not respond to it the call returns `nil` rather than raising an exception.
of classes that do not have ‘Object` among their ancestors, like direct subclasses of `BasicObject`.
34 35 36 |
# File 'lib/hoodie/core_ext/try.rb', line 34 def try(*a, &b) try!(*a, &b) if a.empty? || respond_to?(a.first) end |
#try!(*a, &b) ⇒ Object
Same as #try, but will raise a NoMethodError exception if the receiver is not ‘nil` and does not implement the tried method.
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/hoodie/core_ext/try.rb', line 44 def try!(*a, &b) if a.empty? && block_given? if b.arity.zero? instance_eval(&b) else yield self end else public_send(*a, &b) end end |