From 6a1fb17a25ce7b52b7c5e396adf86ceb96606d64 Mon Sep 17 00:00:00 2001 From: Bryan Duxbury Date: Tue, 21 Sep 2010 16:30:58 +0000 Subject: [PATCH] THRIFT-909. rb: allow block argument to struct constructor This patch allows the user to pass a block to generated structs' constructors. The block will receive and instance of the new object. Patch: Michael Stockton git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@999487 13f79535-47bb-0310-9956-ffa450edef68 --- lib/rb/lib/thrift/struct.rb | 4 +++- lib/rb/spec/struct_spec.rb | 23 ++++++++++++++++------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/lib/rb/lib/thrift/struct.rb b/lib/rb/lib/thrift/struct.rb index 9ee6912d..0525f539 100644 --- a/lib/rb/lib/thrift/struct.rb +++ b/lib/rb/lib/thrift/struct.rb @@ -21,7 +21,7 @@ require 'set' module Thrift module Struct - def initialize(d={}) + def initialize(d={}, &block) # get a copy of the default values to work on, removing defaults in favor of arguments fields_with_defaults = fields_with_default_values.dup @@ -50,6 +50,8 @@ module Thrift instance_variable_set("@#{name}", (default_value.dup rescue default_value)) end end + + yield self if block_given? end def fields_with_default_values diff --git a/lib/rb/spec/struct_spec.rb b/lib/rb/spec/struct_spec.rb index 59a40181..04f55ca6 100644 --- a/lib/rb/spec/struct_spec.rb +++ b/lib/rb/spec/struct_spec.rb @@ -31,13 +31,22 @@ class ThriftStructSpec < Spec::ExampleGroup end it "should initialize all fields to defaults" do - struct = Foo.new - struct.simple.should == 53 - struct.words.should == "words" - struct.hello.should == Hello.new(:greeting => 'hello, world!') - struct.ints.should == [1, 2, 2, 3] - struct.complex.should be_nil - struct.shorts.should == Set.new([5, 17, 239]) + validate_default_arguments(Foo.new) + end + + it "should initialize all fields to defaults and accept a block argument" do + Foo.new do |f| + validate_default_arguments(f) + end + end + + def validate_default_arguments(object) + object.simple.should == 53 + object.words.should == "words" + object.hello.should == Hello.new(:greeting => 'hello, world!') + object.ints.should == [1, 2, 2, 3] + object.complex.should be_nil + object.shorts.should == Set.new([5, 17, 239]) end it "should not share default values between instances" do -- 2.17.1