Skip to content

Instantly share code, notes, and snippets.

@doomspork
Last active December 17, 2015 21:29
Show Gist options
  • Save doomspork/5675420 to your computer and use it in GitHub Desktop.
Save doomspork/5675420 to your computer and use it in GitHub Desktop.
require 'clerk'
require 'csv'
class ClassIdTransformer
def self.transform(id)
case id.to_i
when 1
"Fighter"
when 2
"Mage"
when 3
"Cleric"
else
"Guard"
end
end
end
class NPCLoader < Clerk::Base
template do |t|
t.ignored
t.named :name
t.named :race
t.named :gender
t.named :class
t.ignored
t.grouped(:loot) do |g|
g.named :name
g.named :quantity
end
end
validates_presence_of :name, :race, :class
transforms :'loot/quantity' do |qty|
qty.to_i
end
transforms_with ClassIdTransformer, :class
end
npc_csv_data = <<-END_NPC
1,Fhaemita Dewshining,Half-elf,Female,3,80
2,Ravastine Soulaxe,Dwarf,Female,3,90,Mirthil Axe,1,Gold,2,Silver,21
3,Otifire Smilebeard,Gnome,Male,2,70,Silk Robe,1,Emerald,1,Tapers,10,Spellbook,1
4,Xyrsys Taletreader,Dwarf,Female,6,85,Old Stick,1
END_NPC
npcs = CSV.parse npc_csv_data
loader = NPCLoader.new
loader.load npcs
loader.results
=> [{:name=>"Fhaemita Dewshining",
:race=>"Half-elf",
:gender=>"Female",
:class=>"Cleric",
:loot=>[]},
{:name=>"Ravastine Soulaxe",
:race=>"Dwarf",
:gender=>"Female",
:class=>"Fighter",
:loot=>
[{:name=>"Mirthil Axe", :quantity=>1},
{:name=>"Gold", :quantity=>2},
{:name=>"Silver", :quantity=>21}]},
{:name=>"Otifire Smilebeard",
:race=>"Gnome",
:gender=>"Male",
:class=>"Mage",
:loot=>
[{:name=>"Silk Robe", :quantity=>1},
{:name=>"Emerald", :quantity=>1},
{:name=>"Tapers", :quantity=>10},
{:name=>"Spellbook", :quantity=>1}]},
{:name=>"Xyrsys Taletreader",
:race=>"Dwarf",
:gender=>"Female",
:class=>"Guard",
:loot=>[{:name=>"Old Stick", :quantity=>1}]}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment