2017-02-06 11 views
5

私の質問は、nokogiriを使用しているhappymapperのフォークであるhttps://github.com/dam5s/happymapperのドキュメントに基づいて出力を作成することに関連しています。Happymapper(fork) - 複数のクラスからの出力

私はドキュメンテーションで2つの例を使用しています。これは私の例です。

xml_doc = <<EOF 
<address location='home'> 
    <street>Milchstrasse</street> 
    <street>Another Street</street> 
    <housenumber>23</housenumber> 
    <postcode>26131</postcode> 
    <city>Oldenburg</city> 
    <country code="de">Germany</country> 
</address> 
EOF 

class Address 
    include HappyMapper 

    tag 'address' 

    element :housenumber, Integer, :tag => "housenumber" 
end 

class Country 
    include HappyMapper 

    tag 'country' 

    attribute :code, String 
    content :name, String 

end 

outputs = Country.parse(xml_doc) 
outputs.each do |output| 
    puts output.code 
    puts output.name 
    puts output.housenumber 
end 

の予想される出力

de 
Germany 
23 

マイ出力

[email protected] ~/race (master●)$ ruby read_race.rb   [ruby-2.4.0p0] 
de 
Germany 
read_race.rb:49:in `block in <main>': undefined method `housenumber' for #<Country:0x0055e55facf798 @code="de", @name="Germany"> (NoMethodError) 
    from read_race.rb:46:in `each' 
    from read_race.rb:46:in `<main>' 
+1

おそらく、 'element:housenumber、Integer、:tag =>" housenumber "を' Country'クラスに追加する必要があります。 'housenumber'というメソッドを定義していないので、それから呼び出すことができます。 –

+0

100%確かではない良い例は、あまり明確ではありません。 1つの例では、クラス内で関数を作成しますが、これはhas_many要素用です。 – sayth

答えて

3

これは、多かれ少なかれ直接コピー/ペーストのドキュメントからです。私はそれがあなたが望むものを得ることを願っています。

最も重要な部分は、Address.parse代わりのCountry.parseを呼び出し、output.country.codeの代わりoutput.codeとしてCountryフィールドを参照しています。次に、Happymapperのreadmeで宣伝されているのとまったく同じように動作します。

#!/usr/bin/env ruby 

require 'happymapper' 

ADDRESS_XML_DATA = <<XML 
<root> 
    <address location='home'> 
     <street>Milchstrasse</street> 
     <street>Another Street</street> 
     <housenumber>23</housenumber> 
     <postcode>26131</postcode> 
     <city>Oldenburg</city> 
     <country code="de">Germany</country> 
    </address> 
</root> 
XML 

class Country 
    include HappyMapper 

    tag 'country' 

    attribute :code, String 
    content :name, String 
end 

class Address 
    include HappyMapper 

    tag 'address' 

    has_many :streets, String, :tag => 'street' 

    def streets 
    @streets.join('\n') 
    end 

    element :postcode , String , :tag => 'postcode' 
    element :housenumber, String , :tag => 'housenumber' 
    element :city  , String , :tag => 'city' 
    element :country , Country, :tag => 'country' 
end 

outputs = Address.parse(ADDRESS_XML_DATA) 
outputs.each do |output| 
    puts output.country.code 
    puts output.country.name 
    puts output.housenumber 
end 
+0

私のコードのほとんどが出力に寄与していないので、私はそれをはっきりと引き離してきました。 – sayth

+0

通りを使用しない場合は、通り、郵便番号、住宅番号、都市に関するすべてを安全に削除できます – nus