Builder fragment wrapped by template (Ruby blocks question)?

T

tharrison

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,900
Latest member
Nell636132

Latest Threads

Top