Module: LazyAttributes::Base::ClassMethods

Defined in:
lib/lazy_attributes.rb

Instance Method Summary collapse

Instance Method Details

#column_names_without_lazyObject



40
41
42
# File 'lib/lazy_attributes.rb', line 40

def column_names_without_lazy
  column_names - self._lazy_attributes
end

#column_symbols_without_lazyObject



44
45
46
# File 'lib/lazy_attributes.rb', line 44

def column_symbols_without_lazy
  column_names_without_lazy.map(&:to_sym)
end

#lazy_attributes(*attrs) ⇒ Object



11
12
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
# File 'lib/lazy_attributes.rb', line 11

def lazy_attributes(*attrs)
  if self._lazy_attributes.empty?
    default_scope do
      select(column_names_without_lazy.map do |column_name|
        "#{table_name}.#{column_name}"
      end)
    end
  end
  attrs = attrs.map(&:to_s)
  attrs.each do |attr|
    attr = attr.to_sym
    define_method(attr) do
      unless has_attribute?(attr)
        self.class.define_attribute_method(attr)
        write_attribute(attr, self.class.where(id: self.id).pluck(attr).first)
      end
      read_attribute(attr)
    end
    define_method(:"#{attr}=") do |val|
      unless has_attribute?(attr)
        self.class.define_attribute_method(attr)
        write_attribute(attr, self.class.where(id: self.id).pluck(attr).first)
      end
      write_attribute(attr, val)
    end
  end
  self._lazy_attributes += attrs
end