Class: JSONCSVConverter::Converter
- Inherits:
-
Object
- Object
- JSONCSVConverter::Converter
- Defined in:
- lib/json_csv_converter/converter.rb
Instance Attribute Summary collapse
-
#csv_table ⇒ Object
readonly
Returns the value of attribute csv_table.
-
#json ⇒ Object
readonly
Returns the value of attribute json.
-
#mapping ⇒ Object
readonly
Returns the value of attribute mapping.
Instance Method Summary collapse
- #csv_to_json ⇒ Object
-
#initialize(json, csv, mapping, options = {}) ⇒ Converter
constructor
A new instance of Converter.
- #json_to_csv ⇒ Object
Constructor Details
#initialize(json, csv, mapping, options = {}) ⇒ Converter
Returns a new instance of Converter.
7 8 9 10 11 12 13 14 |
# File 'lib/json_csv_converter/converter.rb', line 7 def initialize(json,csv,mapping,={}) @json_path = json @json_name = [:json_name] || File.basename(json,'.json') @json = JSON.load(File.open(json)) @csv_path = csv @csv_table = CSV.table(csv,) @mapping = YAML.load_file(mapping) end |
Instance Attribute Details
#csv_table ⇒ Object (readonly)
Returns the value of attribute csv_table.
5 6 7 |
# File 'lib/json_csv_converter/converter.rb', line 5 def csv_table @csv_table end |
#json ⇒ Object (readonly)
Returns the value of attribute json.
5 6 7 |
# File 'lib/json_csv_converter/converter.rb', line 5 def json @json end |
#mapping ⇒ Object (readonly)
Returns the value of attribute mapping.
5 6 7 |
# File 'lib/json_csv_converter/converter.rb', line 5 def mapping @mapping end |
Instance Method Details
#csv_to_json ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/json_csv_converter/converter.rb', line 40 def csv_to_json mapped_csv = @csv_table.dup mapped_csv.each do |row| row_hash = row.to_hash mapped_row_hash = {} row_hash.each do |key,value| mapped_row_hash[@mapping["to_csv"][key.to_s]] = value end @json[@json_name] << mapped_row_hash end @json end |
#json_to_csv ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/json_csv_converter/converter.rb', line 21 def json_to_csv headers = @csv_table.headers @json[@json_name].each do |element| row = CSV::Row.new([],[]) headers.each do |column| column_hash = {} mapping_key = @mapping["to_csv"][column.to_s] if mapping_key.kind_of? Array column_hash[column] = mapping_key.inject(element) {|whole,map_key| whole[map_key]} else column_hash[column] = element[mapping_key] end row << column_hash end @csv_table << row end self end |