2012-01-13 44 views
0

我有一個方法返回一個哈希,然後我在xml文件中寫入哈希條目。 Iwant這個哈希轉換爲對象來存儲條目,然後將其寫入xml文件... 我當前的代碼是這樣的將哈希重構爲對象

def entry(city) 
      { 
      :loc => ActionController::Integration::Session.new.url_for(:controller => 'cities', :action => 'show', :city_name => city.name, :host => @country_host.value), 
      :changefreq => 0.8, 
      :priority => 'monthly', 
      :lastmod => city.updated_at 
      } 
end 

的write_entry方法是我的作家類中寫入此項以XML文件

def write_entry(entry) 
     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 = entry[ node.to_sym ] 
     end 
     end 
     url.to_xml 
    end 

感謝

+0

哈希*是一個對象。你究竟想要完成什麼? – 2012-01-13 12:24:31

+0

我想要做另一個類來映射城市類中的條目並將其寫入xml文件。 類似於我的入口方法Map.new(...) – gikian 2012-01-13 12:26:00

回答

1

我可能是方式在這裏下車,但好像你正在試圖做的是這樣的:

首先,弄清楚作爲新對象的類名有什麼意義。我與入學準備,因爲這是你的方法的名稱:

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文檔作爲參數。

+0

非常感謝你:) – gikian 2012-01-13 14:31:24

+0

沒問題!如果您有興趣閱讀更多關於此主題的內容,我推薦Jay Fields的「Refactoring Ruby」。 – 2012-01-13 20:28:38

+0

感謝您的建議,我會毫不猶豫地看看它 – gikian 2012-01-13 22:28:23