# Builder fragment wrapped by template (Ruby blocks question)?

**URL:** <https://www.ruby-forum.com/t/builder-fragment-wrapped-by-template-ruby-blocks-question/126718>\
**Category:** Ruby\
**Created:** [January 21, 2008, 5:26pm UTC](https://www.ruby-forum.com/t/builder-fragment-wrapped-by-template-ruby-blocks-question/126718 "2008-01-21T17:26:08Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tharrison](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/9e8a1a/32.png) [@tharrison](https://www.ruby-forum.com/u/tharrison)\
**Post date:** [January 21, 2008, 5:26pm UTC](https://www.ruby-forum.com/t/builder-fragment-wrapped-by-template-ruby-blocks-question/126718/1 "2008-01-21T17:26:08Z")

</div>

I am calling an API that wants XML. There are several different  
methods (submit, status, fetch) that all expect the same XML block,  
surrounding the specific method. I would like to be able to declare  
the Builder inside a method and pass a unique Builder chunk as a block  
to be yielded from within.

This is one example: the first five lines and the last two are always  
the same

def self.build\_fetch\_request(thing\_to\_fetch\_id)  
xml\_out = ‘’  
xml = Builder::XmlMarkup.new(:target =\> xml\_out, :indent =\>  
2, :level =\> 2)  
xml.instruct!  
xml.myapi {  
xml.apikey(‘super-duper-secret’)  
xml.fetch {  
xml.thing(thing\_to\_fetch\_id)  
}  
}  
xml\_out  
end

So it seems like I should be able to do something like

def self.build\_request\_template  
xml\_out = ‘’  
xml = Builder::XmlMarkup.new(:target =\> xml\_out, :indent =\>  
2, :level =\> 2)  
xml.instruct!  
xml.myapi {  
xml.apikey(‘super-duper-secret’)  
yield # execute my specific code here  
}  
xml\_out  
end

and call it like

def self.build\_fetch\_request(thing\_to\_fetch\_id)  
self.build\_request do  
xml.fetch {  
xml.thing(thing\_to\_fetch\_id)  
}  
end  
end

But of course my block variable, “xml” (a Builder instance) is not in  
scope. I could do this easily the old Java (or C, C++ whatever) way.  
But I suspect Ruby has some clever, elegant way.

What brilliant Ruby expert can show me the clever, elegant way to do  
this?

Thanks a bunch,

Tom
