From 7c812a11d90fef8e5d6b786739cbcc43ff955e99 Mon Sep 17 00:00:00 2001 From: Christopher Bertels Date: Sat, 25 Jun 2011 00:49:00 +0200 Subject: [PATCH] Added Object#do: which allows message cascading style code by calling the code with the receiver as the receiver (using Block#call_with_receiver:). --- lib/object.fy | 22 ++++++++++++++++++++++ tests/object.fy | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/object.fy b/lib/object.fy index a900039f..d103c5c4 100644 --- a/lib/object.fy +++ b/lib/object.fy @@ -542,4 +542,26 @@ class Object { { return 0 } if: (self == other) return 1 # greater or equal to other } + + def do: block { + """ + @block @Block@ to be called in the context of @self. + + Helper method that calls @block with @self as the receiver. + This allows message cascading like code, e.g.: + + some_complex_object do: { + method_1: arg1 + method_2: arg2 + method_3: arg3 + } + + # this is the same as: + some_complex_object method_1: arg1 + some_complex_object method_2: arg2 + some_complex_object method_3: arg3 + """ + + block call_with_receiver: self + } } \ No newline at end of file diff --git a/tests/object.fy b/tests/object.fy index 26d7d40a..96359628 100644 --- a/tests/object.fy +++ b/tests/object.fy @@ -193,4 +193,18 @@ FancySpec describe: Object with: { self test is == 42 test is == (self test) } + + it: "should call a given block in the context of the receiver (like a message cascade)" for: 'do: when: { + arr = [] + arr do: { + << 1 + << 2 + << 3 + select!: 'even? + } + arr is == [2] + arr do: { + is == [2] # same + } + } }