How to create a custom CSV formatter?

307 views
Skip to first unread message

Jose Piccioni

unread,
Jul 20, 2018, 2:59:06 PM7/20/18
to Grape Framework Discussion
Hi there,

I am not being able to find clear documentation on how to create a custom formatter. Where should I put that code (assuming a rails app)?
How would a csv formatter look like (even a superbasic) one. I intend to build a simple get endpoint that returns entities (using grape-entities) in a CSV file:

something like:
name, age, gender
Bob,34,male
Lisa,25,female

This is my endpoint:

     content_type :csv, 'text/csv'                                              
     default_format :csv               
                                               
     # ---------------------------                                              
     # GET /api/public/users                                            
     # ---------------------------                                  
                                                                    
     desc 'Return users as csv'
                  
     get '/' do                          
       header['Content-Disposition'] = 'attachment; filename=file.csv'
       present [Users.all], with: UsersEntity 
     end                     

Regards,
Jose.

Daniel D.

unread,
Jul 23, 2018, 6:58:33 AM7/23/18
to ruby-...@googlegroups.com
Start by not mixing entities and present and one of the many to_csv gems (haven't tried a specific one) that lets you just do "to_csv" on the ActiveRecord result, so:

content_type :csv, "application/csv"
formatter :csv, ->(object, env) { object.to_csv }

If you have a working result maybe contribute it to https://github.com/ruby-grape/grape-on-rack or https://github.com/ruby-grape/grape-on-rails for the next person. I can help in a pull request if you get stuck too. 

--
You received this message because you are subscribed to the Google Groups "Grape Framework Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-grape+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

dB. | Moscow - Geneva - Seattle - New York
code.dblock.org - t:@dblockdotorg - ig:@artdblockdotorgartsy.net - github/dblock
PS: I'm running the NYC TCS Marathon in 2018 for TeamForKids charity. Please donate here.

Reply all
Reply to author
Forward
0 new messages