Giter Club home page Giter Club logo

comma's Introduction

Comma

A library to generate comma seperated value (CSV) for Ruby objects like ActiveRecord and Array

Gem Version Build Status Code Climate

Getting Started

Prerequisites

You need to use ruby 3.0 or later. If you generate CSV from ActiveRecord models, you need to have ActiveRecord 6.0 or later.

Installing

Comma is distributed as a gem, best installed via Bundler.

Include the gem in your Gemfile:

gem 'comma', '~> 4.8.0'

Or, if you want to live life on the edge, you can get master from the main comma repository:

gem 'comma',  git: 'git://github.com/comma-csv/comma.git'

Then, run bundle install.

Usage

See this page for usages.

Running the tests

To run the test suite across multiple gem file sets, we're using Appraisal, use the following commands:

$ bundle exec appraisal install
$ bundle exec appraisal rake spec

Contributing

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Authors

  • Marcus Crafter - Initial work
  • Tom Meier - Initial work
  • Eito Katagiri

License

This project is licensed under the MIT License - see the MIT-LICENSE file fore details.

comma's People

Contributors

adamlogic avatar astevens avatar bquorning avatar coreyward avatar crafterm avatar danabrit avatar dannyben avatar dependabot[bot] avatar eitoball avatar epdejager avatar igorkasyanchuk avatar lackac avatar mfazekas avatar nickhammond avatar npverni avatar olleolleolle avatar oneroyalace avatar plancien avatar reidab avatar seanabrahams avatar spdawson avatar stefanpenner avatar stepahn avatar swdyh avatar tommeier avatar trappist avatar vdesjardins avatar xaviershay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

comma's Issues

has_many through output

I'm trying to output something like this:
user have many custom_values
custom_values belong to custom fields
I want to export in a csv all the custom_values for all the custom_fields

Something like
class User < ActiveRecord::Base
has_many :custom_values
belongs_to :account
comma do
name
account.custom_fields.each do |cf|
custom_value :for => {:custom_field_id => cf.id}, :name => cf.name
end
end
end

Any ideas on how I can achieve this?

Migrate to GitHub Actions

travis-ci.org will be shutting down in several weeks, with all accounts migrating to travis-ci.com.

Getting values for has_many

Hi,

I have a Person class that has many Cars and l want to show the Car number plates for a person how do l do this all l can seem to do is get the size

DEPRECATION WARNING: class_inheritable_attribute is deprecated

When using under Rails 3.1, the following dep warning will be displayed:

DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from <top (required)> at /Users/karl/lazerwiz/config/application.rb:7)

The offending line is in lib/comma.rb:5

Not sure how to fix it.

Does it stream?

I'm looking for a solution compatible with rails streaming, there's no mention in the readme...

crash when fastercsv is not installed

On a machine without FasterCSV, we got this stack trace:

*** Exception NameError in PhusionPassenger::Railz::ApplicationSpawner (uninitialized constant Error) (process 31643):
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:443:in load_missing_constant' from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:80:inconst_missing'
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:92:in const_missing' from /usr/lib/ruby/gems/1.8/gems/comma-0.3.2/lib/comma.rb:16 from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:ingem_original_require'
from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in polyglot_original_require' from /usr/lib/ruby/gems/1.8/gems/polyglot-0.3.1/lib/polyglot.rb:64:inrequire'
from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:156:in `require'

It goes on, but the key line is the one where Comma tries to rescue Error, which doesn't exist. Should probably be Exception or StandardError, or MissingSourceFile, or just 'rescue e'.

CSV::MalformedCSVError

Hi, i am able to import 1000s of records through CSV. I am having fields like email, name, address...
In csv file we will enter address as:
[email protected],Tom Cruise,"2-3-44, New York, USA"
If we miss closing quotation as:
"2-3-44, New York, USA #without closing quotations

I am getting the error as:

CSV::MalformedCSVError in Administration::CollegeController#import_csv
Illegal quoting in line 2.

I want an flash error message instead of error page.

Here is my controller code:

def import_csv
if params[:file].blank?
flash[:error] = "Select a CSV file to upload data."
redirect_to :back
elsif params[:file].original_filename.split('.').last != "csv"
flash[:error] = "Please upload valid csv file."
redirect_to :back
else
n = not_valid = 0
col2 = []
errors = ""
CSV.foreach(params[:file].tempfile) do |row|
if n == 0
n += 1
next
end
col1 = import_from_csv(row)
unless col1.valid?
not_valid += 1
col1.errors.full_messages.each{|m| errors << " At Line : #{n+1}
#{m}
" }
end
col2 << col1
n += 1
end
unless not_valid >= 1
col2.each(&:save)
redirect_to administration_college_users_path,:notice => "#{n-1} fields imported successfully"
else
@errors = "Errors:
#{errors}"
render :load_csv
end
end
end
private
def import_from_csv(row)
College.new( :contact_email => row[0],:name => row[1], :address=>row[2])
end

Please try to help me out..

Thanks,
Raj

Header extraction failing with helper class

We use a helper class to extract our csv formatings from our model class. This will break from versions 3.1 onwards, 3.0.6 was the last working version.

Model:

class Article < ActiveRecord::Base
  belongs_to :brand
  belongs_to :category

  comma do
    article_no 'Article-No'
    csv_formatter brand_name: 'Marke', model_name: 'Variante'
  end
protected
  def csv_formatter
    @csv_formatter ||= ArticleCsvFormatter.new(self, self.category, self.brand)
  end
end

Helper:

class ArticleCsvFormatter
  def initialize(article, category, brand)
    @article = article
    @category = category
    @brand = brand
  end

  def brand_name
    @brand.name
  end

  def model_name
    @category.model_name if @category
  end
end

Error message:
NoMethodError: undefined method `klass' for nil:NilClass

Stacktrace:

/gems/comma-3.2.0/lib/comma/header_extractor.rb:45 in "get_association_class"
/gems/comma-3.2.0/lib/comma/header_extractor.rb:25 in "block (2 levels) in method_missing"
/gems/comma-3.2.0/lib/comma/header_extractor.rb:24 in "each"
/gems/comma-3.2.0/lib/comma/header_extractor.rb:24 in "block in method_missing"
/gems/comma-3.2.0/lib/comma/header_extractor.rb:21 in "each"
/gems/comma-3.2.0/lib/comma/header_extractor.rb:21 in "method_missing"
[/app/models/article.rb:81 in "block in &lt;class:Article&gt;"](https://github.com/reverseretail/buddy/tree/master/app/models/article.rb#L81)
/gems/comma-3.2.0/lib/comma/extractor.rb:15 in "instance_eval"
/gems/comma-3.2.0/lib/comma/extractor.rb:15 in "results"
/gems/comma-3.2.0/lib/comma/object.rb:24 in "extract_with"
/gems/comma-3.2.0/lib/comma/object.rb:17 in "to_comma_headers"
/gems/comma-3.2.0/lib/comma/generator.rb:30 in "append_csv"
/gems/comma-3.2.0/lib/comma/generator.rb:21 in "block in run"
[/usr/local/lib/ruby/1.9.1/csv.rb:1243 in "generate"](https://github.com/reverseretail/buddy/tree/master/usr/local/lib/ruby/1.9.1/csv.rb#L1243)
/gems/comma-3.2.0/lib/comma/generator.rb:21 in "run"
/gems/comma-3.2.0/lib/comma/relation.rb:3 in "to_comma"
[/lib/services/excel_export.rb:53 in "export_csv"](https://github.com/reverseretail/buddy/tree/master/lib/services/excel_export.rb#L53)
[/app/controllers/articles_controller.rb:42 in "block (2 levels) in index"](https://github.com/reverseretail/buddy/tree/master/app/controllers/articles_controller.rb#L42)
/gems/actionpack-3.2.15/lib/action_controller/metal/mime_responds.rb:196 in "call"
/gems/actionpack-3.2.15/lib/action_controller/metal/mime_responds.rb:196 in "respond_to"
[/app/controllers/articles_controller.rb:39 in "index"](https://github.com/reverseretail/buddy/tree/master/app/controllers/articles_controller.rb#L39)
/gems/actionpack-3.2.15/lib/action_controller/metal/implicit_render.rb:4 in "send_action"
/gems/actionpack-3.2.15/lib/abstract_controller/base.rb:167 in "process_action"
/gems/actionpack-3.2.15/lib/action_controller/metal/rendering.rb:10 in "process_action"
/gems/actionpack-3.2.15/lib/abstract_controller/callbacks.rb:18 in "block in process_action"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:502 in "_run__258860530__process_action__818133685__callbacks"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:405 in "__run_callback"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:385 in "_run_process_action_callbacks"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:81 in "run_callbacks"
/gems/actionpack-3.2.15/lib/abstract_controller/callbacks.rb:17 in "process_action"
/gems/actionpack-3.2.15/lib/action_controller/metal/rescue.rb:29 in "process_action"
/gems/actionpack-3.2.15/lib/action_controller/metal/instrumentation.rb:30 in "block in process_action"
/gems/activesupport-3.2.15/lib/active_support/notifications.rb:123 in "block in instrument"
/gems/activesupport-3.2.15/lib/active_support/notifications/instrumenter.rb:20 in "instrument"
/gems/activesupport-3.2.15/lib/active_support/notifications.rb:123 in "instrument"
/gems/actionpack-3.2.15/lib/action_controller/metal/instrumentation.rb:29 in "process_action"
/gems/actionpack-3.2.15/lib/action_controller/metal/params_wrapper.rb:207 in "process_action"
/gems/activerecord-3.2.15/lib/active_record/railties/controller_runtime.rb:18 in "process_action"
/gems/newrelic_rpm-3.6.9.171/lib/new_relic/agent/instrumentation/rails3/action_controller.rb:38 in "block in process_action"
/gems/newrelic_rpm-3.6.9.171/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:339 in "perform_action_with_newrelic_trace"
/gems/newrelic_rpm-3.6.9.171/lib/new_relic/agent/instrumentation/rails3/action_controller.rb:37 in "process_action"
/gems/actionpack-3.2.15/lib/abstract_controller/base.rb:121 in "process"
/gems/actionpack-3.2.15/lib/abstract_controller/rendering.rb:45 in "process"
/gems/rack-mini-profiler-0.1.31/Ruby/lib/mini_profiler/profiling_methods.rb:79 in "block in profile_method"
/gems/actionpack-3.2.15/lib/action_controller/metal.rb:203 in "dispatch"
/gems/actionpack-3.2.15/lib/action_controller/metal/rack_delegation.rb:14 in "dispatch"
/gems/actionpack-3.2.15/lib/action_controller/metal.rb:246 in "block in action"
/gems/actionpack-3.2.15/lib/action_dispatch/routing/route_set.rb:73 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/routing/route_set.rb:73 in "dispatch"
/gems/actionpack-3.2.15/lib/action_dispatch/routing/route_set.rb:36 in "call"
/gems/journey-1.0.4/lib/journey/router.rb:68 in "block in call"
/gems/journey-1.0.4/lib/journey/router.rb:56 in "each"
/gems/journey-1.0.4/lib/journey/router.rb:56 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/routing/route_set.rb:608 in "call"
/gems/newrelic_rpm-3.6.9.171/lib/new_relic/rack/error_collector.rb:50 in "call"
/gems/newrelic_rpm-3.6.9.171/lib/new_relic/rack/agent_hooks.rb:28 in "call"
/gems/newrelic_rpm-3.6.9.171/lib/new_relic/rack/browser_monitoring.rb:23 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/best_standards_support.rb:17 in "call"
/gems/rack-1.4.5/lib/rack/etag.rb:23 in "call"
/gems/rack-1.4.5/lib/rack/conditionalget.rb:25 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/head.rb:14 in "call"
/gems/remotipart-1.2.1/lib/remotipart/middleware.rb:27 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/params_parser.rb:21 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/flash.rb:242 in "call"
/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:210 in "context"
/gems/rack-1.4.5/lib/rack/session/abstract/id.rb:205 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/cookies.rb:341 in "call"
/gems/activerecord-3.2.15/lib/active_record/query_cache.rb:64 in "call"
/gems/activerecord-3.2.15/lib/active_record/connection_adapters/abstract/connection_pool.rb:479 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/callbacks.rb:28 in "block in call"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:405 in "_run__348730247__call__821351200__callbacks"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:405 in "__run_callback"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:385 in "_run_call_callbacks"
/gems/activesupport-3.2.15/lib/active_support/callbacks.rb:81 in "run_callbacks"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/callbacks.rb:27 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/remote_ip.rb:31 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/debug_exceptions.rb:16 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/show_exceptions.rb:56 in "call"
/gems/railties-3.2.15/lib/rails/rack/logger.rb:32 in "call_app"
/gems/railties-3.2.15/lib/rails/rack/logger.rb:16 in "block in call"
/gems/activesupport-3.2.15/lib/active_support/tagged_logging.rb:22 in "tagged"
/gems/railties-3.2.15/lib/rails/rack/logger.rb:16 in "call"
/gems/actionpack-3.2.15/lib/action_dispatch/middleware/request_id.rb:22 in "call"
/gems/rack-1.4.5/lib/rack/methodoverride.rb:21 in "call"
/gems/rack-1.4.5/lib/rack/runtime.rb:17 in "call"
/gems/activesupport-3.2.15/lib/active_support/cache/strategy/local_cache.rb:72 in "call"
/gems/rack-1.4.5/lib/rack/lock.rb:15 in "call"
/gems/rack-ssl-1.3.3/lib/rack/ssl.rb:27 in "call"
/gems/rack-cache-1.2/lib/rack/cache/context.rb:136 in "forward"
/gems/rack-cache-1.2/lib/rack/cache/context.rb:245 in "fetch"
/gems/rack-cache-1.2/lib/rack/cache/context.rb:185 in "lookup"
/gems/rack-cache-1.2/lib/rack/cache/context.rb:66 in "call!"
/gems/rack-cache-1.2/lib/rack/cache/context.rb:51 in "call"
/gems/rack-mini-profiler-0.1.31/Ruby/lib/mini_profiler/profiler.rb:189 in "call"
/gems/railties-3.2.15/lib/rails/engine.rb:484 in "call"
/gems/railties-3.2.15/lib/rails/application.rb:231 in "call"
/gems/railties-3.2.15/lib/rails/railtie/configurable.rb:30 in "method_missing"
[/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/rack/thread_handler_extension.rb:77 in "process_request"](https://github.com/reverseretail/buddy/tree/master/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/rack/thread_handler_extension.rb#L77)
[/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/request_handler/thread_handler.rb:140 in "accept_and_process_next_request"](https://github.com/reverseretail/buddy/tree/master/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/request_handler/thread_handler.rb#L140)
[/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/request_handler/thread_handler.rb:108 in "main_loop"](https://github.com/reverseretail/buddy/tree/master/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/request_handler/thread_handler.rb#L108)
[/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/request_handler.rb:441 in "block (3 levels) in start_threads"](https://github.com/reverseretail/buddy/tree/master/usr/local/lib/ruby/gems/1.9.1/gems/passenger-4.0.5/lib/phusion_passenger/request_handler.rb#L441)

Model and Helper class have been reduced to avoid complexity, line numbers in the stack trace may not coincide, but the error occurs when csv_formatter will be called for the first time.

[REE] 1.8.7 not working on 0.5.2 like suggested

Anonymous contributor via email

The github page for the Comma gem states that comma 0.5.2 is the last version that supports Ruby 1.8.7. I'm trying to run rails 3.2.1, ree 1.8.7 and Comma 0.5.2. Here's the error I receive when I try to fire up webrick or the rails console:

$ rails s
/Users/anon/.rvm/gems/ree-1.8.7-2011.03@anonymous/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:251:in `require': no such file to load -- active_support/core_ext/class/inheritable_attributes (LoadError)
    from /Users/anon/.rvm/gems/ree-1.8.7-2011.03@anonymous/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:251:in `require'
    from /Users/anon/.rvm/gems/ree-1.8.7-2011.03@anonymous/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /Users/anon/.rvm/gems/ree-1.8.7-2011.03@anonymous/gems/activesupport-3.2.1/lib/active_support/dependencies.rb:251:in `require'
    from /Users/anon/.rvm/gems/ree-1.8.7-2011.03@anonymous/gems/comma-0.5.2/lib/comma.rb:27

Is this a common error for this combination of rails and ruby?

Base One CSV Configuration Off of Another

I've got a model that has multiple CSV output types. Each output type adds data to the previous. It would be great if there was a way to keep this code DRY. Perhaps a syntax like:

comma :base do
  first_name
  last_name
  address
end
comma :more do
  extend :base
  city
  state
  zip
end

Exporting with BOM

I was contemplating whether I should open an issue or a question on SO. Apologies if I chose poorly...

Is there anything I need to do in comma config, or the call to "render" in order to get the CSV with BOM? The reason I am asking, is that my users see gibberish when opening with Excel 2010, but it opened nicely when I added the BOM (manually).

I found this post that shows how to do it without comma, but I was hoping to get to something simpler, in the same spirit of comma. Maybe something like:

respond_to do |format|
  format.html { @activities = @activities.page(params[:page]) }
  format.csv  { render :csv => @activities, bom: true } # <--- tadaaa...
end

Comma 2.1.1 not working with Rails 2.3.15?

Hi, I just updated an older app from Rails 2.3.14 to 2.3.15 and I'm now getting a "NoMethodError (undefined method 'status=' for ...): .../comma/render_as_csv.rb:41: in 'render_stream' /.../comma/render_as:csv.rb:25: in render" error, when I try to access the csv version of a controller. The app runs as normal except for that.

I am running comma 2.1.1, fastercsv 1.5.5, Rails 2.3.15 and Ruby 1.8.7.

I've spent a significant amount of time researching (including Google-ing) the issue without any luck. I have tried to use "require 'comma'" and to add ":status => 200" as a render option.

Thank you for your time.

Unable to configure

I am not able to use this gem in my application. Below is the error i am receiving while just accessing my model in ruby console after adding comma block.

NoMethodError: undefined method comma' for #<Class:0x0000010616c388> from /Users/sts-158imac/.rvm/gems/ruby-1.9.3-p125@sh/gems/activerecord-3.2.1/lib/active_record/dynamic_matchers.rb:50:inmethod_missing'

My Model

class JobType < ActiveRecord::Base

#associations

validations

comma do
id
job_number
job_location
start_date
end_date
on_going
end
end

filename option not working for me

Everything works for me using default csv options...
respond_to do |format|
format.csv { render :csv => Order.created_today }
end

However when I add the filename option I get this error:

No comma format for class ActiveRecord::NamedScope::Scope defined for style filenameGenetree_Orders.csv

respond_to do |format|
format.csv { render :csv => Order.created_today.to_comma(:filename => 'Genetree_Orders.csv') }
end

I've looked at the specs and it appears I am calling the code correctly. Any suggestions?

Why does sorting trigger a warning?

Hi,

I just noticed this warning in my logs:

#to_comma is being used on a relation with limit or order clauses. Falling back to iterating with :each. This can cause performance issues.

I am using Comma in Rails, and my controller obtains a list that is not limited, but is sorted.

My questions are:

  1. Why does sorting trigger a warning? I mean, my guess is that in most circumstances, one would want to sort the relation before generating a CSV, otherwise we just get some random database sorting.

  2. If using limit triggers a warning as well, how come all the examples on the wiki page use limit? And same as sorting, why is this considered a warning at all? It is also a desired use case.

Rails 3 - error msg about activesupport

I am trying to use comma in a Rails 3 project. I added the gem to the app's gemfile.

When I try to add the comma ... do end statement to a model, I get a "comma - method undefined" error. So I add a

require 'comma' to the model, which makes the method undefined error go away, but now I get an exception saying "no such file to load - activesupport"

Could you give us step-by-step instructions on how to use comma in a Rails 3 project, please? It requires activesupport, but I believe the way Rails 3 includes activesupport has been changed.

Please help, I'd like to use your great software

Can i dynamically select options for export?

For example I have model Order

class Order < ActiveRecord::Base
  belongs_to :organization

  comma do
    id
    state

    organization :name
    organization :id  
  end
end

Can i pass any options to csv renderer like {:state, organization: [:id]} to export only this fields?

render_as_csv.rb:35

When I downloaded a file, it comes with this line instead the objects

Proc:0x9ce1540@/usr/local/lib/ruby/gems/1.9.1/gems/comma-0.4.1/lib/comma/render_as_csv.rb:35

Someone had this error before?

thanks!

NoMethodError (undefined method `status=' for #<xxxController:0x10b689a50>):

Not sure what happened, but my render :csv doesnt' seem to work

  def index
    @search = UserSearch.new(params[:user_search])
    respond_to do |format|
      format.html do
        @users = @search.users.paginate(:page => params[:page]) 
        render :action => "index"
      end
      format.csv { render :csv => @search.users }
    end
  end

Here is the full output:
https://gist.github.com/2291255

I tried from version 0.4.3 till 2.0 (since I'm running rails 2.3)
Also tried rails 2.3.12 - 2.3.14.

Not sure where to go from here.

Associations failing

Trace shows:

comma (3.1.0) lib/comma/extractors.rb:72:in `get_association_class'
comma (3.1.0) lib/comma/extractors.rb:55:in `block in method_missing'

Code is:

def get_association_class(model_class, association)
      model_class.respond_to?(:reflect_on_association) ?
        model_class.reflect_on_association(arg).klass : nil
    end
  end

In my job.rb model I have:

  belongs_to :customer

And then in Comma:

  comma do 
      customer :first_name
  end

And the error for Rails is :

undefined method `klass' for nil:NilClass

I can't understand why it doesn't recognize my association.

Using comma 3.1.0, Ruby-2.0, Rails 3.2.13

Rails/RSpec/Capybara: Test raises "Missing template errors/internal_server_error}

The CSV export is working nicely, but when trying to test it, I get the following error:

Error during failsafe response: Missing template errors/internal_server_error with {:locale=>[:en], :formats=>[:csv], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :slim, :jbuilder, :coffee, :haml]}.

The spec looks like this:

require 'rails_helper'

describe 'Exporting findings' do
  it 'exports findings to CSV' do
    @project = create :project

    visit project_path(@project)
    click_link 'Export to CSV'

    # Error raised!
  end
end

FindingsController:

class FindingsController < InheritedResources::Base
  load_and_authorize_resource
  belongs_to :project
  respond_to :csv
end

Using comma with padrino ruby framework

I'm currently upgrading a 10 year old padrino app (upgraded before 4 years ago) to padrino 0.15.2 - a sinatra and AR based framework. I'd like to use comma for csv exports (to replace MS deprecated openxml xls formats that are now broken :-/ ).

Because comma hooks into AR, I was hoping I could use it like so:

  # admin/controllers/reports.rb
  get :species_data_dump, :provides => :csv do
    @species = Species.order(:name)

    render csv: @species
  end

Perhaps predictably, I'm getting an error in that it's not expecting an instance variable here, but I imagine that's because I don't know comma internals well enough. Is there a way to hook into the rails magic you built somewhat easily?

Comma uses wrong comma block on single table inheritance in Rails

If a comma block is defined on a super class, but missing in one sub class, the comma block from a wrong subclass is used, instead of the one from the super class.
This behaviour only occurs in a Rails / Active Record environment and is not a general inheritance problem.
To reproduce, execute the tests I added in this commit:
chrisdb@508c159

Comma is not supporting for exporting named scopes in rails 3

I have following code in my controller

my_controller
def export
@variables = Model.scope
respond_to do |format|
format.html # export.html.haml
format.csv do
send_data(@variables.to_comma(:brief))
end
end

and the following error occured
error
No comma format for class ActiveRecord::Relation defined for style brief

can anybody help me out

problem returning the count of a through association

My model has a has_many through association called results. I wanted to return the count of that association as a column in my csv output. The obvious thing to do is to say:

results :count => "Total Results"

However, this causes an error:

ArgumentError (wrong number of arguments (1 for 0))

I'm not sure where it's cropping up exactly, but I found that If I add a method to my class that simply returns the association, like:

def all_results
    results
end

Then, I'm able to use that method in the comma block and it works just fine:

all_results :count => "Total Results"

Thanks for the great gem!

Dynamic Columns with headers

Is there a way to make a block build columns with custom headers. For example i have users that have associated groups. I'd like to be able to cycle through each group and make that a column header and put an X in the column if the user has that group. New groups can be added so making a ton of custom methods seems very inefficient if i can just make one that can handle all of them.

-Thanks

Ruby 2.7 keywaord arguments deprecation warnings

Hi there and first thanks for the gem! 👍

Running it with Ruby 2.7 though I get deprecation warnings:

/usr/local/bundle/gems/comma-4.3.2/lib/comma/generator.rb:21: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
/usr/local/lib/ruby/2.7.0/csv.rb:533: warning: The called method `generate' is defined here

Seems to be this code:

    def run(iterator_method)
      if @filename
        CSV_HANDLER.open(@filename, 'w', @options) { |csv| append_csv(csv, iterator_method) } && (return true)
      else
        CSV_HANDLER.generate(@options) { |csv| append_csv(csv, iterator_method) }
      end
    end

CSV_HANDLER is the stdlib CSV library and according to the generate docs it just passes the arguments on the new which seems to use kwargs.

So the proposed workaround of the warning message of adding ** to the call seems to work/be ok as I assume the @options are settable from users.

Has Many Associations As Columns

Is there a way to show a has many association as columns in an export? Basically i'm trying to have the user export have a column for each group with the header being the group name and the data being the date the group was created. Is there currently a way to do this?

Defining configuration outside of the ActiveRecord model

Does comma have pre-existing support for defining the comma config outside of the ActiveRecord model? For instance, is there an easy way to create an app/serializers folder for this config? I'd prefer to keep it separate if possible, and want to avoid using an include if there's already a way to do this.

Thanks!

Translating boolean values

I have the following to_comma method:

  comma do
    critical Finding.human_attribute_name :critical # bool
    closed Finding.human_attribute_name :closed # bool
  end

This results in true and false items for both critical and closed:

Critical? | Closed?
----------|--------
true      | false
false     | true
false     | false

I'd rather have the name of the attribute instead of true and empty instead of false:

Critical? | Closed?
----------|--------
Critical  |
          | Closed
          |

Or maybe:

Critical?    | Closed?
-------------|--------
Critical     | Not Closed
Not Critical | Closed
Not Critical | Not Closed

I can't find a way to do that in the comma method. Do I miss something?

"type" isn't a missing method

I can't use the :type method defined on my objects unless I patch (or monkey-patch) comma.

Here's my monkey-patch I use in my Rails project: in config/initializers/fix_comma_type_method.rb

module Comma
  class Extractor
    def type(*args)
      method_missing(:type, *args)
    end
  end
end

Fields with line breaks \n

I need to export text fields that contain several line breaks \n. They are not escaped and when transforming to csv, they generate extra rows.

model Profile
  field :description
  # Sample description
  # "Hello,\n I'm here to destroy your CSV export 3:D"
end

Is there a way to escape them ? Or should I just define a description_escaped method that would substitute those \n by another separator ?

Breaking changes?

Hi, just wondering if there were breaking changes between the 3.0.x series and 3.1.x / 3.2.x? There’s no changelog so I’m not sure if I can upgrade safely.

Version 4.3.1 - ArgumentError: Polymorphic association does not support to compute class.

After upgrading from 4.2.0 to 4.3.1 I am getting this error during my tests.

ArgumentError: Polymorphic association does not support to compute class.
  • The error is triggered from the model's comma block.
  • The model has a polymorphic association created by the audited gem.
  • I have tried removing the associated columns from my comma model definition to see if it helps, it did not.
  • Version 4.3.0 is also affected
  • Ruby 2.5.3, Rails 5.2.2.1

data formatting methods not called.

Hello,

I am trying to use a data formatting method across many columns. It looks like that :

def humanize_boolean(boolean)
  unless boolean.nil?
    I18n.t boolean ? 'global.yes' : 'global.no'
  end
end

But when I call it in the comma definition :

comma do
  id Event.human_attribute_name('id')
  name Event.human_attribute_name('name')
  activated Event.human_attribute_name('activated') do |boolean|
    humanize_boolean(boolean)
  end
end

I get a runtime error "Unknown data symbol false" (it can be Unknown data symbol true to, and same thing for integers).

What's odd to me is that if I put the body of humanize_boolean inside of the comma block everything works as intended.

comma do
  id Event.human_attribute_name('id')
  name Event.human_attribute_name('name')
  activated Event.human_attribute_name('activated') do |boolean|
    unless boolean.nil?
      I18n.t boolean ? 'global.yes' : 'global.no'
    end
  end
end

Am I doing something wrong ?

Easy i18n of column headers

Is there an easy way to internationalize column headers? It's not done automatically as it seems, which feels a bit clumsy to me.

class Finding < ActiveRecord::Base
  comma do
    description Finding.human_attribute_name(:description) # Shouldn't this be done automatically?
    boilerplate_copy: BoilerplateCopy.human_attribute_name(:title) # This too?
    boilerplate_copy { |boilerplate_copy| boilerplate_copy.topic.outro } # I guess this can't be done automatically...
  end
end

Rails 3 parameters not working (excl :filename)

It seems that only the filename parameter is working.

{ render :csv => Job.all, :force_quotes => true, :filename => "jobs - #{DateTime.now.to_s(:csv)}"}

This does not force quotes, but the filename gets named correctly.

I also tried:
{ render :csv => Job.all, :write_headers => false, :filename => "jobs - #{DateTime.now.to_s(:csv)}"}
and saw no difference.

Using Rails 3.1. Can anyone test and confirm this for me?

Cheers
Sean

Streaming?

Does 'render' with Comma support streaming? Any ideas how I'd go about doing that? Thanks!

Crash on class-level .to_comma_headers

In version 3.0.6, you could call Foo.to_comma_headers(:stylename). However, at some point between then and 3.2.2, it broke:

> Foo.to_comma_headers(:stylename)
NoMethodError: undefined method `[]' for nil:NilClass
    from /home/ari/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/comma-3.2.2/lib/comma/extractor.rb:15:in `results'
    from /home/ari/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/comma-3.2.2/lib/comma/object.rb:24:in `extract_with'
    from /home/ari/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/comma-3.2.2/lib/comma/object.rb:17:in `to_comma_headers'
    from (irb):3

You can still call to_comma_headers on an instance of Foo though.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.