0

我试图了解 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
4

1 回答 1

4

to 的参数yield将被解析为块的参数。因此,在您的示例中,将gateway值分配给persist块的参数。

于 2012-12-05T04:43:28.070 回答