Class: Datasource::Attributes::Loaded

Inherits:
Object
  • Object
show all
Defined in:
lib/datasource/attributes/loaded.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

._optionsObject

Returns the value of attribute _options.



5
6
7
# File 'lib/datasource/attributes/loaded.rb', line 5

def _options
  @_options
end

Class Method Details

.default_valueObject



15
16
17
# File 'lib/datasource/attributes/loaded.rb', line 15

def default_value
  self._options[:default]
end

.inherited(base) ⇒ Object



7
8
9
# File 'lib/datasource/attributes/loaded.rb', line 7

def inherited(base)
  base._options = (_options || {}).dup
end

.load(collection_context) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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) ⇒ Object



11
12
13
# File 'lib/datasource/attributes/loaded.rb', line 11

def options(hash)
  self._options.merge!(hash)
end