Class: Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-daj/writer.rb

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Writer

Returns a new instance of Writer.



3
4
5
6
7
8
9
# File 'lib/ruby-daj/writer.rb', line 3

def initialize(data)
  if data.nil?
    raise ArgumentError, 'Data is required in order to perform this operation. Please use the following form "daj(your_data) > your_file" and everything should be fine.'
  else
    @data = data
  end
end

Instance Method Details

#write(ext, filename) ⇒ Object

Call operator as writer



15
16
17
18
# File 'lib/ruby-daj/writer.rb', line 15

def write(ext, filename)
  ext = @kind || ext
  RubyDaj::FORMATS.include?(ext) ? send(:"write_#{ext}", filename) : write_plain_text(filename)
end

#write_csv(filename) ⇒ Object



32
33
34
35
36
# File 'lib/ruby-daj/writer.rb', line 32

def write_csv(filename)
  CSV.open(filename, "w") do |csv|
    @data.each {|data| csv << data}
  end
end

#write_csvh(filename) ⇒ Object



38
39
40
41
42
43
# File 'lib/ruby-daj/writer.rb', line 38

def write_csvh(filename)
  CSV.open(filename, "w") do |csv|
    csv << @data.first.keys # adds the attributes name on the first line
    @data.each {|hash| csv << hash.values}
  end
end

#write_json(filename) ⇒ Object



24
25
26
# File 'lib/ruby-daj/writer.rb', line 24

def write_json(filename)
  File.open(filename, "w") {|f| f.puts @data.to_json }
end

#write_plain_text(filename, encoding = 'utf-8') ⇒ Object



20
21
22
# File 'lib/ruby-daj/writer.rb', line 20

def write_plain_text(filename, encoding = 'utf-8')
  File.open(filename, "w:#{encoding}") {|f| f.puts @data }
end

#write_tsv(filename) ⇒ Object



45
46
47
48
49
# File 'lib/ruby-daj/writer.rb', line 45

def write_tsv(filename)
  CSV.open(filename, "w", col_sep: "\t") do |tsv|
    @data.each {|data| tsv << data}
  end
end

#write_tsvh(filename) ⇒ Object



51
52
53
54
55
56
# File 'lib/ruby-daj/writer.rb', line 51

def write_tsvh(filename)
  CSV.open(filename, "w", col_sep: "\t") do |tsv|
    tsv << @data.first.keys # adds the attributes name on the first line
    @data.each {|hash| tsv << hash.values}
  end
end

#write_yml(filename) ⇒ Object



28
29
30
# File 'lib/ruby-daj/writer.rb', line 28

def write_yml(filename)
  File.open(filename, "w") {|f| f.puts @data.to_yaml }
end