Skip to content

Instantly share code, notes, and snippets.

@dkubb
Last active December 26, 2015 23:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkubb/7228155 to your computer and use it in GitHub Desktop.
Save dkubb/7228155 to your computer and use it in GitHub Desktop.
require 'coercible'
class Transformer
include Enumerable
COERCER = Coercible::Coercer.new
COERCIONS = Hash.new(:to_string).update(
id: :to_integer,
updated_on: :to_date,
active: :to_boolean,
)
def initialize(rows)
@rows = rows
end
def each
return to_enum unless block_given?
@rows.each do |row|
yield row.map { |key, value|
COERCER[value.class].public_send(COERCIONS[key], value)
}
end
self
end
end
rows = [
{
id: '1',
name: 'Dan Kubb',
updated_on: '2013-01-01',
active: 'yes',
}
]
Transformer.new(rows)
@warmwaffles
Copy link

class Transformer
  IDENTITY = ->(value) { value }
  COERCER  = Coercible::Coercer.new

  COERCIONS = Hash.new(IDENTITY).update({
    'ga:date'      => ->(value) { Date.strptime(value, '%Y%m%d') },
    'ga:visitors'  => COERCER[String].method(:to_integer),
    'ga:visits'    => COERCER[String].method(:to_integer),
    'ga:newVisits' => COERCER[String].method(:to_integer),
  })

  # @param [Array] columns the array of column names
  # @param [Array] the rows of data
  def self.coerce(columns, rows)
    rows.map do |row|
      hash = columns.zip(row)
      hash.map do |key, value|
        COERCIONS[key][value]
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment