class Datasource::Attributes::Loaded

Attributes

_options[RW]

Public Class Methods

default_value() click to toggle source
# File lib/datasource/attributes/loaded.rb, line 15
def default_value
  self._options[:default]
end
inherited(base) click to toggle source
# File lib/datasource/attributes/loaded.rb, line 7
def inherited(base)
  base._options = (_options || {}).dup
end
load(collection_context) click to toggle source
# File lib/datasource/attributes/loaded.rb, line 19
def load(collection_context)
  loader = collection_context.method(_options[:source])
  args = [collection_context].slice(0, loader.arity) if loader.arity >= 0
  results = loader.call(*args)

  if _options[:group_by]
    results = Array(results)
    send_args = if results.first && results.first.kind_of?(Hash)
      [:[]]
    else
      []
    end

    if _options[:one]
      results.inject(empty_hash) do |hash, r|
        key = r.send(*send_args, _options[:group_by])
        hash[key] = r
        hash
      end
    else
      results.inject(empty_hash) do |hash, r|
        key = r.send(*send_args, _options[:group_by])
        (hash[key] ||= []).push(r)
        hash
      end
    end
  elsif _options[:from] == :array
    Array(results).inject(empty_hash) do |hash, r|
      hash[r[0]] = r[1]
      hash
    end
  else
    set_hash_default(Hash(results))
  end
end
options(hash) click to toggle source
# File lib/datasource/attributes/loaded.rb, line 11
def options(hash)
  self._options.merge!(hash)
end

Private Class Methods

empty_hash() click to toggle source
# File lib/datasource/attributes/loaded.rb, line 61
def empty_hash
  set_hash_default(Hash.new)
end
set_hash_default(hash) click to toggle source
# File lib/datasource/attributes/loaded.rb, line 56
def set_hash_default(hash)
  hash.default = default_value
  hash
end