Class: FileBuilders::JSONFileBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/file_builders/json_file_builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, file_name, options) ⇒ JSONFileBuilder

Returns a new instance of JSONFileBuilder.



9
10
11
12
13
14
# File 'lib/file_builders/json_file_builder.rb', line 9

def initialize(data, file_name, options)
  @data = data
  @file_name = file_name
  @options = options
  @titles = options[:titles]
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



7
8
9
# File 'lib/file_builders/json_file_builder.rb', line 7

def data
  @data
end

#file_nameObject (readonly)

Returns the value of attribute file_name.



7
8
9
# File 'lib/file_builders/json_file_builder.rb', line 7

def file_name
  @file_name
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/file_builders/json_file_builder.rb', line 7

def options
  @options
end

#titlesObject (readonly)

Returns the value of attribute titles.



7
8
9
# File 'lib/file_builders/json_file_builder.rb', line 7

def titles
  @titles
end

Instance Method Details

#export_to_fileObject



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/file_builders/json_file_builder.rb', line 16

def export_to_file
  return puts 'For JSON format titles are required' if titles.empty?

  json_data = data.inject([]) do |result, row|
    result << titles.zip(row).to_h
  end

  File.open(file_name, 'a') do |file|
    file << JSON.pretty_generate(json_data)
  end
end