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 |
# File 'lib/streamingly/serde.rb', line 27 def self.from_csv(string) tokens = CSV.parse_line(string) klass = resolve_class(tokens.first) klass.new(*tokens[1..-1].compact) rescue NameError tokens end |
.from_string_or_csv(string) ⇒ Object
47 48 49 50 51 52 53 54 55 |
# File 'lib/streamingly/serde.rb', line 47 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
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/streamingly/serde.rb', line 35 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
57 58 59 |
# File 'lib/streamingly/serde.rb', line 57 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 |