Skip to content

Instantly share code, notes, and snippets.

@robinclart
Created April 18, 2012 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinclart/2410988 to your computer and use it in GitHub Desktop.
Save robinclart/2410988 to your computer and use it in GitHub Desktop.
A class to parse csv document
Gem::Specification.new do |s|
s.name = "casanova"
s.version = "0.1.0"
s.platform = Gem::Platform::RUBY
s.author = "Robin Clart"
s.email = "robin@clart.be"
s.summary = ""
s.description = ""
s.files = ["casanova.rb"]
s.test_file = "casanova_spec.rb"
s.require_path = "."
s.add_development_dependency "minitest", ["~> 2.12"]
end
#--
# Copyright (c) 2012 Robin Clart
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
# A class to convert CSV document into a nicer format.
#
# Example:
#
# statistics = Casanova.new(document)
# statistics.to_a(:type, :id, :date, :note)
# # => [{:type=>"page", :id=>"21", :date=>"04-04-2012 15:40", :note=>""}, ...]
class Casanova
def initialize(document)
@document = document
end
# Returns an Array of Hashes with the specified keys.
def to_a(*keys)
@document.split("\n").map { |l| Hash[keys.zip(l.split(",", keys.size))] }
end
end
gem "minitest"
require "minitest/autorun"
require File.expand_path("casanova")
describe Casanova do
subject { Casanova.new("page,48,20120327143524\npage,45,20120327143638") }
describe "#to_a" do
let(:keys) { [:type, :ref, :date] }
it "should return an array of hashes with the specified keys" do
subject.to_a(*keys).must_be_instance_of Array
subject.to_a(*keys).first.must_be_instance_of Hash
subject.to_a(*keys).first.length.must_equal 3
subject.to_a(*keys).must_equal [
{ type: "page", ref: "48", date: "20120327143524"},
{ type: "page", ref: "45", date: "20120327143638"}
]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment