Module: ActiveRecord::Collections::Serialization::ClassMethods

Defined in:
lib/active_record/collections/serialization.rb

Instance Method Summary collapse

Instance Method Details

#from_hash(hash) ⇒ Object



13
14
15
16
17
18
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
# File 'lib/active_record/collections/serialization.rb', line 13

def from_hash(hash)
  hash.symbolize_keys! unless hash.is_a?(HashWithIndifferentAccess)

  kollektion = kollektion_from_hash(hash)
  kollektable = kollektable_from_hash(hash)
  collection = kollektion.new(kollektable)
  collection.select!(*hash[:select]) unless hash[:select].empty?
  collection.distinct! if hash[:distinct] == true

  collection.joins!(*hash[:joins]) unless hash[:joins].empty?
  collection.references!(*hash[:references]) unless hash[:references].empty?
  collection.includes!(*hash[:includes]) unless hash[:includes].empty?

  wheres = hash[:where].partition { |w| w.is_a?(Hash) }
  wheres.first.each do |wh|
    if wh.keys.first == :not
      collection.not!(wh[:not])
    else
      collection.where!(wh)
    end
  end
  collection.where!(*hash[:bind].map { |b| b[:value] }.unshift(wheres.last.join(" AND ").gsub(/\$\d/,'?'))) unless wheres.last.empty?

  collection.group!(hash[:group]) unless hash[:group].empty?
  collection.order!(hash[:order]) unless hash[:order].empty?

  collection.limit!(hash[:limit]) unless hash[:limit].nil?
  collection.offset!(hash[:offset]) unless hash[:offset].nil?

  collection
end

#from_json(json) ⇒ Object



9
10
11
# File 'lib/active_record/collections/serialization.rb', line 9

def from_json(json)
  from_hash JSON.load(json)
end

#kollektable_from_hash(hash) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/active_record/collections/serialization.rb', line 53

def kollektable_from_hash(hash)
  kollektable = nil
  kollektable = hash[:collectable] if hash.has_key?(:collectable)
  kollektable = kollektable.constantize unless kollektable.is_a?(Class) || kollektable.nil?
  raise "Invalid collectable model: #{kollektable}" unless kollektable < ActiveRecord::Base
  kollektable
end

#kollektion_from_hash(hash) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/active_record/collections/serialization.rb', line 45

def kollektion_from_hash(hash)
  kollektion = self
  kollektion = hash[:collection] if hash.has_key?(:collection) && !hash[:collection].nil?
  kollektion = kollektion.constantize unless kollektion.is_a?(Class)
  raise "Invalid collection class: #{kollektion}" unless kollektion <= ActiveRecord::Collection
  kollektion
end