Skip to content

Commit

Permalink
Adding compatibility for different encodings - fix mbleigh#31
Browse files Browse the repository at this point in the history
I change the default internal encoding because seed.inspect need to be
properly encoded.
  • Loading branch information
eloyesp committed Dec 11, 2011
1 parent 5ab8e68 commit 0138fd3
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
24 changes: 23 additions & 1 deletion lib/seed-fu/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ class Writer
# @option options [:seed, :seed_once] :seed_type (:seed) The method to use when generating
# seeds. See {ActiveRecordExtension} for details.
# @option options [Array<Symbol>] :constraints ([:id]) The constraining attributes for the seeds
# @option options [String] :encoding The encoding to use in the generated file.
def initialize(options = {})
@options = self.class.default_options.merge(options)
raise ArgumentError, "missing option :class_name" unless @options[:class_name]
set_encoding if @options[:encoding]
end

# Creates a new instance of {Writer} with the `options`, and then calls {#write} with the
Expand All @@ -56,10 +58,11 @@ def write(io_or_filename, &block)
if io_or_filename.respond_to?(:write)
write_to_io(io_or_filename, &block)
else
File.open(io_or_filename, 'w') do |file|
File.open(io_or_filename, "w#{encoding_string}") do |file|
write_to_io(file, &block)
end
end
unset_encoding if @old_encoding
end

# Add a seed. Must be called within a block passed to {#write}.
Expand Down Expand Up @@ -88,6 +91,7 @@ def <<(seed)

def write_to_io(io)
@io, @count = io, 0
@io.write(encoding_comment) if @options[:encoding]
@io.write(file_header)
@io.write(seed_header)
yield(self)
Expand Down Expand Up @@ -128,5 +132,23 @@ def seed_footer
def chunk_this_seed?
@count != 0 && (@count % @options[:chunk_size]) == 0
end

def encoding_string
":#{@options[:encoding]}" if @options[:encoding]
end

def encoding_comment
"# encoding: #{@options[:encoding]}\n"
end

def set_encoding
@old_encoding = Encoding.default_internal
Encoding.default_internal = @options[:encoding]
end

def unset_encoding
Encoding.default_internal = @old_encoding if @old_encoding
end
end
end

14 changes: 14 additions & 0 deletions spec/writer_spec.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# encoding: utf-8
require 'spec_helper'

describe SeedFu::Writer do
Expand Down Expand Up @@ -42,4 +43,17 @@

SeededModel.find(1).title.should == "Dr"
end

it "should support specifying the output encoding to use" do
SeedFu::Writer.write(@file_name, :class_name => 'SeededModel', :encoding => "utf-8") do |writer|
writer << { :id => 1, :title => "Mr" }
writer << { :id => 2, :title => "Máster" }
end

File.read(@file_name).should include("# encoding: utf-8\n")

load @file_name
SeededModel.find(2).title.should == "Máster"
end
end

0 comments on commit 0138fd3

Please sign in to comment.