2012-01-13 10 views
0

ハッシュを返すメソッドがあり、次にxmlファイルにハッシュのエントリを書きます。 write_entry方法は、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 

のようなものです ...エントリを格納し、xmlファイルにそれを書くために、オブジェクトに、このハッシュを変換するIwantファイル

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

ハッシュ*はオブジェクトです。あなたは正確に何を達成しようとしていますか? –

+0

都市クラスのエントリをマップしてxmlファイルに書き込む別のクラスを作成したいと思います。私の入力方法Map.new(...) – gikian

答えて

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を使用するだけでなくすることを更新する必要がありますXML文書を引数として渡します。

+0

あなたに巨大なおかげで:) – gikian

+0

ませんPROBの中にそのような 何か!このテーマについてもっと読むことに興味があるなら、Jay Fieldsの "Refactoring Ruby"をお勧めします。 –

+0

私は間違いなくそれを見ることをお勧めします – gikian

関連する問題