Module: Streamingly::SerDe
- Defined in:
- lib/streamingly/serde.rb
Class Method Summary collapse
- .from_csv(string) ⇒ Object
- .from_string_or_csv(string) ⇒ Object
- .from_tabbed_csv(string) ⇒ Object
- .resolve_class(class_name) ⇒ Object
- .to_csv(record) ⇒ Object
Class Method Details
.from_csv(string) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/streamingly/serde.rb', line 27 def self.from_csv(string) tokens = CSV.parse_line(string) return unless tokens.size > 0 klass = resolve_class(tokens.first) tokens_arr = tokens.to_a tokens_arr.pop while tokens_arr.last.nil? tokens_arr.shift # Remove leading class marker klass.new(*tokens_arr) rescue NameError tokens end |
.from_string_or_csv(string) ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/streamingly/serde.rb', line 51 def self.from_string_or_csv(string) if string.include? ',' # Likely a CSV from_csv(string) # Attempt to parse else string end rescue CSV::MalformedCSVError # Not actually CSV, fallback to string string end |
.from_tabbed_csv(string) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/streamingly/serde.rb', line 39 def self.from_tabbed_csv(string) k, v = string.split("\t", 2) return if k.nil? || v.nil? key = from_string_or_csv(k) value = if v.include? "\t" from_tabbed_csv(v) else from_string_or_csv(v) end KV.new(key, value) end |
.resolve_class(class_name) ⇒ Object
61 62 63 |
# File 'lib/streamingly/serde.rb', line 61 def self.resolve_class(class_name) class_name.split('::').reduce(Kernel) { |parent, element| parent.const_get(element) } end |
.to_csv(record) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/streamingly/serde.rb', line 7 def self.to_csv(record) case record when String record when Streamingly::KV record.to_s when Struct tokens = *record.map { |token| case token when BigDecimal token.to_s('F') else token end } CSV.generate_line( [ record.class.name, *tokens ]).rstrip end end |