a csv to object mapper
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
lib
spec
.gitignore
.rspec
.rvmrc
Gemfile
Gemfile.lock
License
README.textile
Rakefile
virgola.gemspec

README.textile

virgola

CSV to object mapping library.

Author

Vicente Reig Rincón de Arellano

Installation

  $ gem install virgola

Usage

Given the following CSV file

  id,name,email
  1,"Chris Floess",chris@propertybase.com
  2,"Konstantin Krauss",konstantin@propertybase.com
  3,"Vicente Reig",vicente@propertybase.com

You map it to an array of Person objects by specifying to match columns with the `attribute` method.

  class Person
    include Virgola

    attribute :id
    attribute :name
    attribute :email

    after_map :do_something_after_mapping_a_row

    protected

    def do_something_after_mapping_a_row
      puts 'YES, victory!'
    end
  end

You can specify the type for each attribute. If you don’t, it will default to String.

  class Person
    include Virgola

    attribute :id,    type: Integer
    attribute :name,  type: String
    attribute :email, type: String

  end

You actually extract the data and perform the mappings using the Extraction API.

  Person.parse(csv).all   # Array of Person instances mapping the guys above
  Person.parse(csv).count # 3
  Person.parse(csv).each { |pip|
    # do stuff
  }
  Person.parse(csv).in_groups_of(100) { |pips|
    # do stuff
  }

Attributes are overridable.

  class Person
    def email
      "<#{super}>"
    end
  end

  Person.parse(csv).each do |pip|
    puts pip.email # <chris@propertybase.com>, ...
  end

You can access the mappings also as instance attributes.

  class Person
    def email
      "<#{@email}>"
    end
  end

  Person.parse(csv).each do |pip|
    puts pip.email # <chris@propertybase.com>, ...
  end