Skip to content

Commit 052e259

Browse files
enhanced: import and export, and minor corrections
1 parent 92c301e commit 052e259

1 file changed

Lines changed: 38 additions & 6 deletions

File tree

lib/flex-cartesian.rb

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
require 'yaml'
66

77
module FlexOutput
8-
def output(separator: " | ", colorize: false, align: false)
8+
def output(separator: " | ", colorize: false, align: true)
99
return puts "(empty struct)" unless respond_to?(:members) && respond_to?(:values)
1010

1111
values_list = members.zip(values.map { |v| v.inspect })
@@ -35,6 +35,10 @@ def add_function(name, &block)
3535
@derived[name.to_sym] = block
3636
end
3737

38+
def remove_function(name)
39+
@derived.delete(name.to_sym)
40+
end
41+
3842
def cartesian(dims = nil, lazy: false)
3943
dimensions = dims || @dimensions
4044
return nil unless dimensions.is_a?(Hash)
@@ -90,7 +94,7 @@ def progress_each(dims = nil, lazy: false, title: "Processing")
9094
end
9195
end
9296

93-
def output(separator: " | ", colorize: false, align: false, format: :plain, limit: nil)
97+
def output(separator: " | ", colorize: false, align: true, format: :plain, limit: nil)
9498
rows = []
9599
cartesian do |v|
96100
rows << v
@@ -123,14 +127,42 @@ def output(separator: " | ", colorize: false, align: false, format: :plain, limi
123127
end
124128
end
125129

126-
def self.from_json(path)
130+
def import(path, format: :json)
131+
data = case format
132+
when :json
133+
JSON.parse(File.read(path), symbolize_names: true)
134+
when :yaml
135+
YAML.safe_load(File.read(path), symbolize_names: true)
136+
else
137+
raise ArgumentError, "Unsupported format: #{format}. Only :json and :yaml are supported."
138+
end
139+
140+
raise TypeError, "Expected parsed data to be a Hash" unless data.is_a?(Hash)
141+
142+
@dimensions = data
143+
self
144+
end
145+
146+
def export(path, format: :json)
147+
case format
148+
when :json
149+
File.write(path, JSON.pretty_generate(@dimensions))
150+
when :yaml
151+
File.write(path, YAML.dump(@dimensions))
152+
else
153+
raise ArgumentError, "Unsupported format: #{format}. Only :json and :yaml are supported."
154+
end
155+
end
156+
157+
158+
def from_json(path)
127159
data = JSON.parse(File.read(path), symbolize_names: true)
128-
new(data)
160+
@dimensions = data
129161
end
130162

131-
def self.from_yaml(path)
163+
def from_yaml(path)
132164
data = YAML.safe_load(File.read(path), symbolize_names: true)
133-
new(data)
165+
@dimensions = data
134166
end
135167

136168
private

0 commit comments

Comments
 (0)