我可能是方式在這裏下車,但好像你正在試圖做的是這樣的:
首先,弄清楚作爲新對象的類名有什麼意義。我與入學準備,因爲這是你的方法的名稱:
class Entry
end
然後把你的哈希的所有「屬性」,讓他們在對象上閱讀方法:
class Entry
attr_reader :loc, :action, :changefreq, :priority, :lastmod
end
接下來你需要決定如何初始化這個對象。好像你既需要爲這個城市和@country_host:
class Entry
attr_reader :loc, :action, :changefreq, :priority, :last mod
def initialize(city, country_host_value)
@loc = ActionController::Integration::Session.new.url_for(:controller => 'cities', :action => 'show', :city_name => city.name, :host => country_host_value)
@changefreq = 0.8 # might actually want to just make this a constant
@priority = 'monthly' # another constant here???
@lastmod = city.updated_at
end
end
最後你的XML構建方法添加到類:
class Entry
attr_reader :loc, :action, :changefreq, :priority, :last mod
def initialize(city, country_host_value)
@loc = ActionController::Integration::Session.new.url_for(:controller => 'cities', :action => 'show', :city_name => city.name, :host => country_host_value)
@changefreq = 0.8 # might actually want to just make this a constant
@priority = 'monthly' # another constant here???
@lastmod = city.updated_at
end
def write_entry_to_xml(xml_document)
url = Nokogiri::XML::Node.new("url" , xml_document)
%w{loc changefreq priority lastmod}.each do |node|
url << Nokogiri::XML::Node.new(node, xml_document).tap do |n|
n.content = send(node)
end
end
url.to_xml
end
end
現在,您的哈希已被重構,你可以更新你的其他類(ES),以使用新的對象:
class WhateverClassThisIs
def entry(city)
Entry.new(city, @country_host.value)
end
end
目前尚不清楚如何將XML作家方法被調用,但你需要更新,以及使用新的write_entry_to_xm l方法,傳入xml文檔作爲參數。
哈希*是一個對象。你究竟想要完成什麼? – 2012-01-13 12:24:31
我想要做另一個類來映射城市類中的條目並將其寫入xml文件。 類似於我的入口方法Map.new(...) – gikian 2012-01-13 12:26:00