Module: LightRecord

Extended by:
LightRecord
Included in:
LightRecord
Defined in:
lib/light_record.rb

Defined Under Namespace

Modules: RecordAttributes, RelationMethods

Instance Method Summary collapse

Instance Method Details

#base_extended(klass) ⇒ Object

Create LightRecord class based on klass argument



108
109
110
111
112
113
114
115
# File 'lib/light_record.rb', line 108

def base_extended(klass)
  @base_extended ||= {}
  if @base_extended[klass]
    return @base_extended[klass]
  end

  @base_extended[klass] = LightRecord.build_for_class(klass, klass.column_names)
end

#build_for_class(klass, fields) ⇒ Object

Create LightRecord class based on klass argument Used internally by scope#light_records and scope#light_records_each

Parameters:

  • ActiveRecord model

  • list of fields, will be used to define attribute methods

Returns:

  • new class base on klass argument but extended with LightRecord methods



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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/light_record.rb', line 11

def build_for_class(klass, fields)
  new_klass = Class.new(klass) do
    self.table_name = klass.table_name
    self.inheritance_column = nil

    extend LightRecord::RecordAttributes

    define_fields(fields)

    def initialize(data)
      @attributes = data
      @readonly = true
    end

    def read_attribute_before_type_cast(attr_name)
      @attributes[attr_name.to_sym]
    end

    def self.subclass_from_attributes?(attrs)
      false
    end

    def has_attribute?(attr_name)
      @attributes.has_key?(attr_name.to_sym)
    end

    def read_attribute(attr_name)
      @attributes[attr_name.to_sym]
    end

    def _read_attribute(attr_name)
      @attributes.fetch(attr_name.to_sym) { |n| yield n if block_given? }
    end

    def [](attr_name)
      @attributes[attr_name.to_sym]
    end
  
    def attributes
      @attributes
    end

    # to avoid errors when try saving data
    def remember_transaction_record_state
      @_start_transaction_state ||= {}
      super
    end
  end

  if klass.const_defined?(:LightRecord, false)
    new_klass.send(:include, klass::LightRecord)
  elsif klass.superclass.const_defined?(:LightRecord, false)
    new_klass.send(:include, klass.superclass::LightRecord)
  end

  new_klass
end