Class: Object

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

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

Returns:

  • (Boolean)


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

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.



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

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

#deep_dupObject

Object#dup is shallow and therefore useless:

a = { name: { first: ‘Georgi’ } } dupl = a.dup

#this also changes a when it shouldn’t dupl[:first] = ‘Dazen’

a

> :name=>:first=>“Dazen”}

deep_dup fixes this behavior



15
16
17
# File 'lib/inactive_support/object/deep_dup.rb', line 15

def deep_dup
  Marshal.load(Marshal.dump(self))
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]]


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

def identity
  if block_given?
    yield self
  else
    self
  end
end

#present?Boolean

Returns:

  • (Boolean)


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

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.



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

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