class ArrayHasher::Formatter
Constants
- REGEXP_EMPTY
- TYPES
Attributes
cols[RW]
types[RW]
Public Class Methods
new(cols)
click to toggle source
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] ]
# File lib/array_hasher/formatter.rb, line 29 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
Public Instance Methods
define_type(type, &block)
click to toggle source
# File lib/array_hasher/formatter.rb, line 41 def define_type(type, &block) types[type.to_sym] = block end
parse(arr)
click to toggle source
# File lib/array_hasher/formatter.rb, line 45 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