Class: Object

Inherits:
BasicObject
Defined in:
lib/inactive_support/object/try.rb,
lib/inactive_support/object/blank.rb,
lib/inactive_support/object/identity.rb

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/inactive_support/object/blank.rb', line 2

def blank?
  respond_to?(:empty?) ? !!empty? : !self
end

#ctry(*args) ⇒ Object

Chained try allows writing

str.ctry(:mb_chars, :downcase, :dasherize)

instead of

str.try(:mb_chars).try(:downcase).try(:dasherize)

Only works for methods that don’t take any arguments.



25
26
27
28
29
30
31
32
# File 'lib/inactive_support/object/try.rb', line 25

def ctry(*args)
  first, *rest = args
  if rest.any?
    try(first).ctry(*rest)
  else
    try(first)
  end
end

#identityObject

Returns self. If given a block, it works a lot like Object#tap

Examples

[1,2,3,5,7].consecutive_by(&:identity)
=> [[1, 2, 3], [5], [7]]


8
9
10
11
12
13
14
# File 'lib/inactive_support/object/identity.rb', line 8

def identity
  if block_given?
    yield self
  else
    self
  end
end

#present?Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/inactive_support/object/blank.rb', line 6

def present?
  !blank?
end

#try(*args, &b) ⇒ Object

Credit goes to the active_support contributors github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/try.rb

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.



8
9
10
11
12
13
14
# File 'lib/inactive_support/object/try.rb', line 8

def try(*args, &b)
  if args.empty? && block_given?
    yield self
  else
    public_send(*args, &b) if respond_to?(args.first)
  end
end