I’m trying to understand yield in Ruby. In the self.save method of the Gateway class, it has ‘yield gateway’. I understand that when yield is called the block from Person#save is called, but what does ‘gateway’ become in that block? Can you please explain a little with this code example
class Person
attr_accessor :first_name, :last_name, :ssn
def save
Gateway.save do |persist|
persist.subject = self
persist.attributes = [:first_name, :last_name, :ssn]
persist.to = 'http://www.example.com/person'
end
end
end
class Gateway
attr_acessor :subject, :attributes, :to
def self.save
gateway = self.new
yield gateway
gateway.execute
end
def execute
request = Net::HTTP::Post.new(url.path)
attribute_hash = attributes.inject({}) do | result, attribute |
result[attribute.to_s] = subject.send attribute
result
end
request.set_form(attribute_hash)
Net::HTTP.new(url.host, url.post).start { |http| http.request(request) }
end
def url
URI.parse(to)
end
end
The argument to
yieldwill be parsed as an argument to the block. So in your examplegateway‘s value is assigned to thepersistparameter of the block.