Module: AndAnd::ObjectGoodies
- Included in:
- Object
- Defined in:
- lib/redcar/ruby_extensions.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)
-
- (Object) andand(p = nil)
Returns nil if its receiver is nil, regardless of whether nil actually handles the actual method ot what it might return.
-
- (Object) dont(p = nil)
Does not invoke the method or block and returns the receiver.
-
- (Object) me(p = nil)
(also: #tap)
Invokes the method and returns the receiver if nothing is raised.
Instance Method Details
- (Object) andand(p = nil)
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
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/redcar/ruby_extensions.rb', line 78 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 |
- (Object) dont(p = nil)
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
138 139 140 141 142 143 144 145 146 |
# File 'lib/redcar/ruby_extensions.rb', line 138 def dont (p = nil) if block_given? self elsif p self else MockReturningMe.new(self) end end |
- (Object) me(p = nil) 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]
113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/redcar/ruby_extensions.rb', line 113 def me (p = nil) if block_given? yield(self) self elsif p p.to_proc.call(self) self else ProxyReturningMe.new(self) end end |