我试图了解 Ruby 中的产量。在 Gateway 类的 self.save 方法中,它有“yield gateway”。我知道当调用 yield 时 Person#save 的块被调用,但是“网关”在那个块中变成了什么?你能用这个代码示例解释一下吗
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