将哈希重构为Object

时间:2012-01-13 12:19:40

标签: ruby-on-rails ruby

我有一个返回Hash的方法然后在xml文件中写入hash的条目。我希望将此Hash转换为存储条目的对象,然后将其写入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方法在我的writer类中,它将此条目写入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

由于

1 个答案:

答案 0 :(得分:1)

我可能会离开这里,但看起来你要做的就是这样:

首先,找出有意义的新对象的类名。我要使用Entry,因为这是你方法的名称:

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

现在你的哈希已被重构,你可以更新你的其他类以使用新对象:

class WhateverClassThisIs
  def entry(city)
    Entry.new(city, @country_host.value)
  end
end

目前尚不清楚如何调用XML编写器方法,但您还需要更新它以使用新的write_entry_to_xml方法,并将xml文档作为参数传递。