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

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

Returns:



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

Returns:



42
43
44
# File 'lib/hoodie/core_ext/blank.rb', line 42

def present?
  !blank?
end

#try(*a, &b) ⇒ Object

Note:

‘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`.

Parameters:

  • object (String)
  • method (Symbol)


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.

Raises:

  • NoMethodError 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