From 34078b85f15cd1bf41e5b4908dbf8601bbaf16ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Thu, 19 Apr 2018 14:11:36 +0200 Subject: [PATCH] Fix Object.delegate to setter (#5964) --- spec/std/object_spec.cr | 14 ++++++++++++++ src/object.cr | 20 +++++++++++++------- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/spec/std/object_spec.cr b/spec/std/object_spec.cr index 1f2379a56581..6c56faf7e6d8 100644 --- a/spec/std/object_spec.cr +++ b/spec/std/object_spec.cr @@ -98,6 +98,13 @@ private class TestObject end end +private class DelegatedTestObject + delegate "property1=", to: @test_object + + def initialize(@test_object : TestObject) + end +end + private class TestObjectWithFinalize property key : Symbol? @@ -129,6 +136,13 @@ describe Object do end matches.should eq(["l", "l"]) end + + it "delegates setter" do + test_object = TestObject.new + delegated = DelegatedTestObject.new(test_object) + delegated.property1 = 42 + test_object.property1.should eq 42 + end end describe "getter" do diff --git a/src/object.cr b/src/object.cr index 0ed2c0e27525..d2aff018c302 100644 --- a/src/object.cr +++ b/src/object.cr @@ -1083,15 +1083,21 @@ class Object # ``` macro delegate(*methods, to object) {% for method in methods %} - def {{method.id}}(*args, **options) - {{object.id}}.{{method.id}}(*args, **options) - end + {% if method.id.ends_with?('=') %} + def {{method.id}}(arg) + {{object.id}}.{{method.id}} arg + end + {% else %} + def {{method.id}}(*args, **options) + {{object.id}}.{{method.id}}(*args, **options) + end - def {{method.id}}(*args, **options) - {{object.id}}.{{method.id}}(*args, **options) do |*yield_args| - yield *yield_args + def {{method.id}}(*args, **options) + {{object.id}}.{{method.id}}(*args, **options) do |*yield_args| + yield *yield_args + end end - end + {% end %} {% end %} end