module PluckToHash::ClassMethods

Public Instance Methods

pluck_to_hash(*keys) { |value| ... } click to toggle source
# File lib/pluck_to_hash.rb, line 7
def pluck_to_hash(*keys)
  block_given = block_given?
  hash_type = keys[-1].is_a?(Hash) ? keys.pop.fetch(:hash_type,HashWithIndifferentAccess) : HashWithIndifferentAccess

  keys, formatted_keys = format_keys(keys)
  keys_one = keys.size == 1

  pluck(*keys).map do |row|
    value = hash_type[formatted_keys.zip(keys_one ? [row] : row)]
    block_given ? yield(value) : value
  end
end
Also aliased as: pluck_h
pluck_to_struct(*keys) { |value| ... } click to toggle source
# File lib/pluck_to_hash.rb, line 20
def pluck_to_struct(*keys)
  struct_type = keys[-1].is_a?(Hash) ? keys.pop.fetch(:struct_type,Struct) : Struct
  block_given = block_given?
  keys, formatted_keys = format_keys(keys)
  keys_one = keys.size == 1

  struct = struct_type.new(*formatted_keys)
  pluck(*keys).map do |row|
    value = keys_one ? struct.new(*[row]) : struct.new(*row)
    block_given ? yield(value) : value
  end
end
Also aliased as: pluck_s

Private Instance Methods

format_keys(keys) click to toggle source
# File lib/pluck_to_hash.rb, line 38
def format_keys(keys)
  if keys.blank?
    [column_names, column_names]
  else
    [
      keys,
      keys.map do |k|
        case k
        when String
          k.split(/\bas\b/i)[-1].strip.to_sym
        when Symbol
          k
        end
      end
    ]
  end
end
get_correct_hash_type(hash, hash_type) click to toggle source
# File lib/pluck_to_hash.rb, line 34
def get_correct_hash_type(hash, hash_type)
  hash_type == HashWithIndifferentAccess ? hash.with_indifferent_access : hash
end
pluck_h(*keys)
Alias for: pluck_to_hash
pluck_s(*keys)
Alias for: pluck_to_struct