Builder fragment wrapped by template (Ruby blocks question)?

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs