Class: ArrayHasher::Formatter
- Inherits:
-
Object
- Object
- ArrayHasher::Formatter
- Defined in:
- lib/array_hasher/formatter.rb
Constant Summary collapse
- REGEXP_EMPTY =
/\A\s*\z/- TYPES =
{ int: Proc.new {|v| (v.nil? || v =~ REGEXP_EMPTY) ? nil : v.gsub(/[^\d]+/, '').to_i }, float: Proc.new {|v| (v.nil? || v =~ REGEXP_EMPTY) ? nil : v.gsub(/[^\d\.]+/, '').to_f }, string: Proc.new {|v| v.to_s }, time: Proc.new {|v| v ? Time.parse(v) : nil } }
Instance Attribute Summary collapse
-
#cols ⇒ Object
Returns the value of attribute cols.
-
#types ⇒ Object
Returns the value of attribute types.
Instance Method Summary collapse
- #define_type(type, &block) ⇒ Object
-
#initialize(cols) ⇒ Formatter
constructor
cols: [ [], # ignore this col [:name, :string], [:amount, :int], [:type], # don’t change val [:other, Proc {|v| v.to_i % 2}] # convert val by proc [:all, nil, range: 0..-1] ].
- #parse(arr) ⇒ Object
Constructor Details
#initialize(cols) ⇒ Formatter
cols:
[
[], # ignore this col
[:name, :string],
[:amount, :int],
[:type], # don't change val
[:other, Proc {|v| v.to_i % 2}] # convert val by proc
[:all, nil, range: 0..-1]
]
25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/array_hasher/formatter.rb', line 25 def initialize(cols) @types = TYPES.clone @cols = cols.map do |name, type, opts| [ name ? name.to_sym : nil, (type.nil? || type.is_a?(Proc)) ? type : type.to_sym, (opts || {}).each_with_object({}) {|kv, r| r[kv[0].to_sym] = kv[1] } ] end end |
Instance Attribute Details
#cols ⇒ Object
Returns the value of attribute cols.
5 6 7 |
# File 'lib/array_hasher/formatter.rb', line 5 def cols @cols end |
#types ⇒ Object
Returns the value of attribute types.
5 6 7 |
# File 'lib/array_hasher/formatter.rb', line 5 def types @types end |
Instance Method Details
#define_type(type, &block) ⇒ Object
37 38 39 |
# File 'lib/array_hasher/formatter.rb', line 37 def define_type(type, &block) types[type.to_sym] = block end |
#parse(arr) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/array_hasher/formatter.rb', line 41 def parse(arr) cols.each_with_index.each_with_object({}) do |col_and_index, result| col_opts, index = col_and_index name, type, opts = col_opts opts ||= {} next if name.nil? range = opts[:range] || index val = range.is_a?(Array) ? arr.slice(*range) : arr[range] result[name] = if type.is_a?(Proc) type.call(val) elsif type && (block = types[type.to_sym]) block.call(val) else val end end end |