Class: Decombobulate
- Inherits:
-
Object
- Object
- Decombobulate
- Defined in:
- lib/decombobulate.rb,
lib/decombobulate/version.rb
Defined Under Namespace
Classes: Error
Constant Summary collapse
- VERSION =
"0.1.4"
Instance Attribute Summary collapse
-
#headers ⇒ Object
readonly
Returns the value of attribute headers.
-
#rows ⇒ Object
readonly
Returns the value of attribute rows.
Instance Method Summary collapse
-
#initialize(json) ⇒ Decombobulate
constructor
A new instance of Decombobulate.
- #to_csv(file_name = nil) ⇒ Object
Constructor Details
#initialize(json) ⇒ Decombobulate
Returns a new instance of Decombobulate.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/decombobulate.rb', line 13 def initialize(json) # Parse the JSON if we need to json = Json.parse(json) if json.is_a?(String) # Yes, I tried a case/when statement but for some reason that doesn't work when looking at class types columns = json_to_csv(json) @rows = [] if columns.is_a?(Array) merged_columns = {} # Iterate through the array, finding each key, adding it to the headers row if it's not there already # then merge them columns.each do |entry| entry.keys.each do |key| merged_columns[key] = [] unless merged_columns.has_key?(key) merged_columns[key] << entry[key] merged_columns[key] = merged_columns[key].flatten end end columns = merged_columns end # 6.) Now we have a hash of @columns, we need to turn it into rows # We're going to assume that all the @columns are the same length # So we'll just iterate over the first column and add the values to the row @headers = columns.keys.map(&:to_s) columns[columns.keys.first].size.times do |index| @rows << columns.keys.map { |key| columns[key][index] } end end |
Instance Attribute Details
#headers ⇒ Object (readonly)
Returns the value of attribute headers.
11 12 13 |
# File 'lib/decombobulate.rb', line 11 def headers @headers end |
#rows ⇒ Object (readonly)
Returns the value of attribute rows.
11 12 13 |
# File 'lib/decombobulate.rb', line 11 def rows @rows end |
Instance Method Details
#to_csv(file_name = nil) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/decombobulate.rb', line 45 def to_csv(file_name = nil) if file_name.nil? csv_final = CSV.generate(encoding: "UTF-8") do |csv| csv << @headers @rows.each do |row| csv << row end end else CSV.open(file_name, "wb", encoding: "UTF-8") do |csv| csv << @headers @rows.each do |row| csv << row end end return true end csv_final end |