Builder fragment wrapped by template (Ruby blocks question)?

Discussion in 'Ruby' started by tharrison, Jan 21, 2008.

  1. tharrison

    tharrison Guest

    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
    tharrison, Jan 21, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Arjen
    Replies:
    3
    Views:
    419
    Scott Allen
    Feb 27, 2005
  2. Phlip
    Replies:
    5
    Views:
    545
    Stefan Behnel
    Jan 13, 2010
  3. matt
    Replies:
    1
    Views:
    233
    George Ogata
    Aug 6, 2004
  4. Lyes Amazouz
    Replies:
    2
    Views:
    158
    Lyes Amazouz
    Aug 20, 2008
  5. Steven Taylor
    Replies:
    9
    Views:
    231
    Brian Candler
    Apr 27, 2009
Loading...

Share This Page