Advertisement
twinfacer

parser

Dec 12th, 2012
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.38 KB | None | 0 0
  1. require "rexml/document"
  2. include REXML
  3. class CardInfo
  4.     attr :rules, :name, :cost, :type, :subtypes
  5.     def initialize(name , cost = "" , rules = [],  types = {})
  6.         @name = name
  7.         @cost = cost
  8.         @rules = rules
  9.         @type = types['type']
  10.         @subtypes = types['subtypes']
  11.     end
  12.     def to_s
  13.         puts "\"#{@name}\"" + " #{@cost}"
  14.         @subtypes.empty? ? puts("#{@type}") : puts("#{@type}" + " - " + "#{@subtypes.join(" ")}")
  15.         puts "#{@rules.join("\n")}"
  16.     end
  17. end
  18. class CardParser
  19.     def self.parseFile(path)
  20.         cards = []
  21.         doc = Document.new File.open(path, "r")
  22.         doc.root.elements.to_a("card").each { |x| cards << parseCard(x)}
  23.         cards
  24.     end
  25.     def self.parseCard(card)
  26.         rules = []
  27.         card.elements["rulelist"].nil? ? rules = [] : card.elements["rulelist"].elements.to_a.each {|rule| rules << rule.text}
  28.         types = []
  29.         card.elements["typelist"].nil? ? types = {} : types = parseType(card.elements["typelist"].to_a)
  30.         card.elements["cost"].nil? ? cost = "" : cost = card.elements["cost"].text
  31.         CardInfo.new(card.elements["name"].text, cost, rules, types )
  32.     end
  33.     def self.parseType(typelist)
  34.         types = {"type" => "","subtypes" => []}
  35.         typelist.each {
  36.             |type|
  37.             if type.class == REXML::Element
  38.                 type.attributes['type'] == "card" ? types["type"] = type.text : types["subtypes"] << type.text
  39.             end
  40.         }
  41.         types
  42.     end
  43. end
  44.  
  45. infos = CardParser.parseFile("cards.xml")
  46. infos.each {|c| c.to_s}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement