A library for generating comma-separated values (CSV) from Ruby objects, arrays, and supported ORM collections.
You need Ruby 3.0 or later.
For Rails / ActiveRecord integration, this repository is currently tested against ActiveRecord and Rails 6.0 through 7.1 on Ruby 3.0 through 3.4.
Comma is distributed as a gem, best installed via Bundler.
Include the gem in your Gemfile:
gem'comma','~> 4.9.0'Or, if you want to live life on the edge, you can get master from the main comma repository:
gem'comma',git: 'https://github.com/comma-csv/comma.git'Then, run bundle install.
Define a CSV format on your object with comma. Calling to_comma on a single object returns the row values, while calling it on an array or supported collection generates CSV output:
classUserattr_reader:first_name,:last_namedefinitialize(first_name,last_name)@first_name=first_name@last_name=last_nameendcommadofirst_namelast_namefull_name'Name'enddeffull_name"#{first_name}#{last_name}".stripendenduser=User.new('Ada','Lovelace')user.to_comma# => ["Ada", "Lovelace", "Ada Lovelace"]users=[User.new('Ada','Lovelace'),User.new('Grace','Hopper')]users.to_comma# => "First name,Last name,Name\nAda,Lovelace,Ada Lovelace\nGrace,Hopper,Grace Hopper\n"You can also define named styles and select them when generating CSV:
classUsercomma:shortdofirst_namelast_nameendendusers.to_comma(:short)In Rails controllers, requiring the gem registers render csv: support:
defindexrendercsv: User.allendSee the wiki for more usage examples.
Install dependencies:
bundle install
bundle exec appraisal installRun the default test suite and linter:
bundle exec rspec spec
bundle exec rubocop -PRun a single example:
bundle exec rspec spec/comma/comma_spec.rb:205To run the test suite across the Rails / ActiveRecord gemfile matrix, this repository uses Appraisal:
bundle exec appraisal rake specYou can also run a specific spec under one appraisal:
bundle exec appraisal rails7.1.3 bundle exec rspec spec/controllers/users_controller_spec.rbPlease make sure bundle exec rspec spec, bundle exec rubocop -P, and any relevant bundle exec appraisal ... commands pass before opening a pull request.
We use SemVer for versioning. For the versions available, see the tags on this repository.
- Marcus Crafter - Initial work
- Tom Meier - Initial work
- Eito Katagiri
This project is licensed under the MIT License - see the MIT-LICENSE file for details.