Class: Object

Inherits:
BasicObject
Defined in:
lib/gorillib/object/try.rb,
lib/gorillib/object/blank.rb,
lib/gorillib/object/try_dup.rb

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:



11
12
13
# File 'lib/gorillib/object/blank.rb', line 11

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:



24
25
26
# File 'lib/gorillib/object/blank.rb', line 24

def present?
  not blank?
end

#try(*a, &b) ⇒ Object

Invokes the method identified by the symbol +method+, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

Unlike that method however, a +NoMethodError+ exception will not be raised and +nil+ will be returned instead, if the receiving object is a +nil+ object or NilClass.

If try is called without a method to call, it will yield any given block with the object.

==== Examples

Without +try+ @person && @person.name or @person ? @person.name : nil

With +try+ @person.try(:name)

+try+ also accepts arguments and/or a block, for the method it is trying Person.try(:find, 1) @people.try(:collect) {|p| p.name}

Without a method argument try will yield to the block unless the receiver is nil.

@person.try { |p| "#Object.pp.first_name #Object.pp.last_name" }

+try+ behaves like +Object#send+, unless called on +NilClass+.



29
30
31
32
33
34
35
36
37
# File 'lib/gorillib/object/try.rb', line 29

def try(*a, &b)
  if a.empty? && block_given?
    yield self
  elsif !a.empty? && !respond_to?(a.first)
    nil
  else
    __send__(*a, &b)
  end
end

#try_dupObject

Override this in a child if it cannot be dup'ed

Returns:



5
6
7
# File 'lib/gorillib/object/try_dup.rb', line 5

def try_dup
  self.dup
end