How do I access a variable inside the method I'm calling in a block I'm passing to it?

StackOverflow https://stackoverflow.com/questions/22880705

  •  28-06-2023
  •  | 
  •  

Question

I'm writing a wrapper for an XML API using Nokogiri to build the XML for submission.

In order to keep my code DRY, I'm using custom blocks for the first time and just getting to grips with how to pass variables back and forth and how that works.

What I'm doing at the moment is this:

# Generic action
def action(xml, action_title, test=false)
  xml.request do
    xml.login do
      xml.username("my_user")
      xml.password("my_pass")
    end
    xml.action(action_title)
    xml.params do
      yield
    end
  end
end

# Specific action
def get_users(city = "", gender = "")
  build = Nokogiri::XML::Builder.new do |xml|
    action(xml, "getusers") do
      xml.city(city) unless city.blank?
      xml.gender(gender) unless gender.blank?
    end
  end
  do_stuff_to(build)
end

Ideally, I'd like to the specific action method to look like this:

def get_users(city = "", gender = "")
  action("getusers") do |xml|
    xml.city(city) unless city.blank?
    xml.gender(gender) unless gender.blank?
  end
end

In doing so, I'd want the other logic currently in the specific action method to be moved to the generic action method with the generic action method returning the results of do_stuff_to(build).

What I'm struggling with is how to pass the xml object from action() back to get_users(). What should action() look like in order to achieve this?

Was it helpful?

Solution

Turns out this was quite simple. The action method needs to be changed so it looks like this:

def action(action_title)
  build = Nokogiri::XML::Builder.new do |xml|
    xml.request do
      xml.login do
        xml.username("my_user")
        xml.password("my_pass")
      end
      xml.action(action_title)
      xml.params do
        yield xml
      end
    end
  end
  do_stuff_to(build)
end

That meant the specific action method could be called like this to the same effect:

def get_users(city = "", gender = "")
  action("getusers") do |xml|
    xml.city(city) unless city.blank?
    xml.gender(gender) unless gender.blank?
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top