我是新來的,我希望我能得到我的問題的答案。 我有三個班。Ruby中的產量以及塊如何工作
- 亞軍
- 作家
- 公司
在亞軍類我有
writer = Writer.new(directory + datasource.downcase + ".xml")
ds = ("Sitemap::" + datasource).constantize.new(country_version, directory, country_host)
writer.fill do
ds.yield_data {|entry| writer.write_entry(entry)}
end
Yeild_data是類公司
write_entry是類Writer
以下是類公司代碼
class Company
def initialize(country_version, directory, country_host)
@country_version = country_version
@directory = directory
@country_host = country_host
end
def yield_data
::Company.find_each(:conditions => {:country_version_id => @country_version.id}) do |company|
output = yield entry(company)
puts output
end
end
private
def entry(company)
{
:url => ActionController::Integration::Session.new.url_for(:controller => 'companies', :action => 'show', :company_name => company.name, :host => @country_host.value),
:frequency => 0.8,
:priority => 'monthly',
:lastmod => company.updated_at
}
end
end
以下是一流作家
class Writer
include ActionController::UrlWriter
def initialize(filepath)
@filepath = RAILS_ROOT + filepath
@xml_document = Nokogiri::XML::Document.new
end
def fill
File.open(@filepath,"w") do |f|
f.write(%[<?xml version="1.0" encoding="UTF-8"?>\n])
f.write(%[<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n])
yield self
f.write(%[</urlset>])
f.close
end
end
def write_entry(entry)
node = Nokogiri::XML::Node.new("url", @xml_document)
node["loc"]= entry[:url]
node["lastmod"]= entry[:lastmod].to_s
node["changefreq"] = entry[:frequency].to_s
node["priority"] = entry[:priority].to_s
node.to_xml
#@filepath.write(node)
end
end
請回答我以下的問題:
- 究竟會一代產量條目(公司)迴歸(在公司類)
- 什麼會產生自我回報(在作家類)
- 我怎麼能寫節點XML文件
難道你只是*運行*代碼,看看它返回什麼? – 2011-12-28 11:28:03
我運行的代碼,但我與輸出混淆? – wearybands 2011-12-28 12:09:23
實際上在另一個塊內有塊,它讓我感到困惑 – wearybands 2011-12-28 12:10:20