Skip to content

Instantly share code, notes, and snippets.

@lucashungaro
Created November 8, 2012 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lucashungaro/4036126 to your computer and use it in GitHub Desktop.
Save lucashungaro/4036126 to your computer and use it in GitHub Desktop.
class CardData
def initialize(node)
@card_data = node
end
def name
@card_data.search("name").text
end
def image
@card_data.search("set").attribute("picURL").text
end
def set
@card_data.search("set").text
end
def color
@card_data.search("color").text
end
def manacost
@card_data.search("manacost").text
end
def card_type
@card_data.search("type").text
end
def text
@card_data.search("text").text
end
def loyalty
@card_data.search("loyalty").text
end
def power
@card_data.search("pt").split("/").first
end
def toughness
@card_data.search("pt").split("/").last
end
// se não quiser ficar chamando um por um
// isso também pode ser dinâmico, usando uma constante ou pegando os métodos locais exceto o construtor
def attributes
{
:name => name,
:image => image,
:set => set,
:color => color,
:manacost => manacost,
:card_type => card_type,
:text => text,
:loyalty => loyalty,
:power => power,
:toughness => toughness
}
end
end
class CardXmlParser
def initialize(path, engine = Nokogiri::XML)
@path = path
@engine = engine
parse!
end
def each_card(&block)
@parsed_xml.map do |card|
yield CardData.new(@parsed_xml.new(card))
end
end
private
def parse!
@parsed_xml = @engine(File.open(@path)).search("card")
end
end
parser = CardXmlParser.new("path")
parser.each_card { |card_data| Card.create!(card.<attribute>,..., :without_protection => true) }
ou
parser.each_card { |card_data| Card.create!(card.attributes, :without_protection => true) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment