Module: AndAnd::ObjectGoodies

Included in:
Object
Defined in:
lib/andand.rb

Overview

This module is included in Object, so each of these methods are added to Object when you require 'andand'. Each method is an adverb: they are intended to be enchained with another method, such as receiver.adverb.method

The purpose of an adverb is to modify what the primary method returns.

Adverbs also take blocks or procs, passing the receiver as an argument to the block or proc. They retain the same semantics with a block or proc as they do with a method. This behaviour weakly resembles a monad.

Instance Method Summary collapse

Instance Method Details

#andand(p = nil) ⇒ Object

Returns nil if its receiver is nil, regardless of whether nil actually handles the actual method ot what it might return.

'foo'.andand.size => 3
nil.andand.size => nil
'foo'.andand { |s| s << 'bar' } => 'foobar'
nil.andand { |s| s << 'bar' } => nil

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/andand.rb', line 23

def andand (p = nil)
  if self
    if block_given?
      yield(self)
    elsif p
      p.to_proc.call(self)
    else
      self
    end
  else
    if block_given? or p
      self
    else
      MockReturningMe.new(self)
    end
  end 
end

#dont(p = nil) ⇒ Object

Does not invoke the method or block and returns the receiver. Useful for comemnting stuff out, especially if you are using #me for debugging purposes: change the .me to .dont and the semantics of your program are unchanged.

[1, 2, 3, 4, 5].me { |x| p x }
  => prints and returns the array
[1, 2, 3, 4, 5].dont { |x| p x }
  => returns the array without printing it

83
84
85
86
87
88
89
90
91
# File 'lib/andand.rb', line 83

def dont (p = nil)
  if block_given?
    self
  elsif p
    self
  else
    MockReturningMe.new(self)
  end
end

#me(p = nil) ⇒ Object Also known as: tap

Invokes the method and returns the receiver if nothing is raised. Therefore, the purpose of calling the method is strictly for side effects. In the block form, it resembles #tap from Ruby 1.9, and is useful for debugging. It also resembles #returning from Rails, with slightly different syntax.

Object.new.me do |o|
  def o.foo
    'foo'
  end
end
  => your new object

In the method form, it is handy for chaining methods that don't ordinarily return the receiver:

[1, 2, 3, 4, 5].me.pop.reverse
  => [4, 3, 2, 1]

58
59
60
61
62
63
64
65
66
67
68
# File 'lib/andand.rb', line 58

def me (p = nil)
  if block_given?
    yield(self)
    self
  elsif p
    p.to_proc.call(self)
    self
  else
    ProxyReturningMe.new(self)
  end
end