Skip to content

Commit

Permalink
add option to prepend utf8 bom
Browse files Browse the repository at this point in the history
- rename add_bom to with_bom
- add spec for with_bom
- change to use expect syntax
  • Loading branch information
DannyBen authored and eitoball committed Jun 16, 2020
1 parent c7f1768 commit 57ccb5f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/comma.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ module Comma
ActionController::Renderers.add :csv do |obj, options|
filename = options[:filename] || 'data'
extension = options[:extension] || 'csv'

mime_type = if Rails.version >= '5.0.0'
options[:mime_type] || Mime[:csv]
else
options[:mime_type] || Mime::CSV
end
with_bom = options.delete(:with_bom) || false

# Capture any CSV optional settings passed to comma or comma specific options
csv_options = options.slice(*CSV_HANDLER::DEFAULT_OPTIONS.merge(Comma::DEFAULT_OPTIONS).keys)
Expand All @@ -50,6 +50,7 @@ module Comma
end
end
data = obj.to_comma(csv_options)
data = "\xEF\xBB\xBF#{data}" if with_bom
disposition = "attachment; filename=\"#{filename}.#{extension}\""
send_data data, type: mime_type, disposition: disposition
end
Expand Down
12 changes: 12 additions & 0 deletions spec/controllers/users_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ def get_(name, **args)
expect(response.content_type).to eq 'text/plain'
end

it 'should allow bom to be set' do
get :with_custom_options, :format => :csv, :custom_options => { :with_bom => true }

expected_content =<<-CSV.gsub(/^\s+/,'')
\xEF\xBB\xBFFirst name,Last name
Fred,Flintstone
Wilma,Flintstone
CSV

expect(response.body). to eq expected_content
end

describe 'headers' do
it 'should allow toggling on' do
get_ :with_custom_options, format: :csv, params: { custom_options: { write_headers: 'true' } }
Expand Down

0 comments on commit 57ccb5f

Please sign in to comment.