Module: NoBrainer::Document::LazyFetch::ClassMethods

Defined in:
lib/no_brainer/document/lazy_fetch.rb

Instance Method Summary collapse

Instance Method Details

#allObject



67
68
69
70
71
# File 'lib/no_brainer/document/lazy_fetch.rb', line 67

def all
  criteria = super
  criteria = criteria.lazy_fetch(*self.fields_to_lazy_fetch) if self.fields_to_lazy_fetch.present?
  criteria
end

#field(attr, options = {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/no_brainer/document/lazy_fetch.rb', line 31

def field(attr, options={})
  super
  attr = attr.to_s

  case options[:lazy_fetch]
  when true  then subclass_tree.each { |subclass| subclass.fields_to_lazy_fetch << attr }
  when false then subclass_tree.each { |subclass| subclass.fields_to_lazy_fetch.delete(attr) }
  end

  inject_in_layer :lazy_fetch do
    # Lazy loading can also specified through criteria, we have to define
    # this method regardless of the provided options.
    define_method("#{attr}") do
      return super() unless @lazy_fetch

      begin
        super()
      rescue NoBrainer::Error::MissingAttribute => e
        raise e unless attr.in?(@lazy_fetch)
        reload(:pluck => attr, :keep_ivars => true)
        @lazy_fetch.delete(attr)
        clear_missing_field(attr)
        retry
      end
    end
  end
end

#inherited(subclass) ⇒ Object



26
27
28
29
# File 'lib/no_brainer/document/lazy_fetch.rb', line 26

def inherited(subclass)
  subclass.fields_to_lazy_fetch = self.fields_to_lazy_fetch.dup
  super
end

#remove_field(attr, options = {}) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/no_brainer/document/lazy_fetch.rb', line 59

def remove_field(attr, options={})
  subclass_tree.each { |subclass| subclass.fields_to_lazy_fetch.delete(attr.to_s) }
  inject_in_layer :lazy_fetch do
    remove_method("#{attr}")
  end
  super
end