Class: Datasource::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/datasource/base.rb,
lib/datasource/attributes/loader.rb,
lib/datasource/attributes/query_attribute.rb,
lib/datasource/attributes/computed_attribute.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scope, adapter = nil) ⇒ Base



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/datasource/base.rb', line 72

def initialize(scope, adapter = nil)
  @adapter = adapter || self.class.default_adapter
  @scope =
    if self.class._update_scope
      self.class._update_scope.call(scope)
    else
      scope
    end
  @expose_attributes = []
  @expose_associations = {}
end

Class Attribute Details

._associationsObject

Returns the value of attribute _associations.



4
5
6
# File 'lib/datasource/base.rb', line 4

def _associations
  @_associations
end

._attributesObject

Returns the value of attribute _attributes.



4
5
6
# File 'lib/datasource/base.rb', line 4

def _attributes
  @_attributes
end

._loadersObject

Returns the value of attribute _loaders.



4
5
6
# File 'lib/datasource/base.rb', line 4

def _loaders
  @_loaders
end

._update_scopeObject

Returns the value of attribute _update_scope.



4
5
6
# File 'lib/datasource/base.rb', line 4

def _update_scope
  @_update_scope
end

.orm_klassObject



23
24
25
# File 'lib/datasource/base.rb', line 23

def orm_klass
  fail Datasource::Error, "Model class not set for #{name}. You should define it:\nclass YourDatasource\n  @orm_klass = MyModelClass\nend"
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



70
71
72
# File 'lib/datasource/base.rb', line 70

def adapter
  @adapter
end

#expose_associationsObject (readonly)

Returns the value of attribute expose_associations.



70
71
72
# File 'lib/datasource/base.rb', line 70

def expose_associations
  @expose_associations
end

#expose_attributesObject (readonly)

Returns the value of attribute expose_attributes.



70
71
72
# File 'lib/datasource/base.rb', line 70

def expose_attributes
  @expose_attributes
end

#scopeObject (readonly)

Returns the value of attribute scope.



70
71
72
# File 'lib/datasource/base.rb', line 70

def scope
  @scope
end

Class Method Details

.computed(name, *_deps) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/datasource/attributes/computed_attribute.rb', line 22

def self.computed(name, *_deps)
  deps = _deps.select { |dep| dep.kind_of?(Hash) }
  _deps.reject! { |dep| dep.kind_of?(Hash) }
  unless _deps.empty?
    self_key = default_adapter.get_table_name(orm_klass)
    deps.push(self_key => _deps)
  end

  klass = Class.new(Attributes::ComputedAttribute) do
    depends *deps
  end

  attribute name, klass
end

.consumer_adapterObject



19
20
21
# File 'lib/datasource/base.rb', line 19

def consumer_adapter
  @consumer_adapter = Datasource::ConsumerAdapters::ActiveModelSerializers
end

.default_adapterObject



13
14
15
16
17
# File 'lib/datasource/base.rb', line 13

def default_adapter
  @adapter ||= begin
    Datasource::Adapters.const_get(Datasource::Adapters.constants.first)
  end
end

.inherited(base) ⇒ Object



7
8
9
10
11
# File 'lib/datasource/base.rb', line 7

def inherited(base)
  base._attributes = (_attributes || {}).dup
  base._associations = (_associations || {}).dup
  base._loaders = (_loaders || {}).dup
end

.loader(name, _options = {}, &block) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/datasource/attributes/loader.rb', line 60

def self.loader(name, _options = {}, &block)
  klass = Class.new(Attributes::Loader) do
    # depends deps
    options(_options)
    self._load_proc = block
  end
  @_loaders[name.to_sym] = klass
end

.query(name, deps = nil, value = nil, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/datasource/attributes/query_attribute.rb', line 20

def self.query(name, deps = nil, value = nil, &block)
  klass = Class.new(Attributes::QueryAttribute) do
    depends deps if deps

    if block
      define_singleton_method(:select_value, &block)
    else
      define_singleton_method(:select_value) { value }
    end
  end
  attribute name, klass
end

.reflection_select(reflection, parent_select, assoc_select) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/datasource/base.rb', line 27

def reflection_select(reflection, parent_select, assoc_select)
  # append foreign key depending on assoication
  if reflection[:macro] == :belongs_to
    parent_select.push(reflection[:foreign_key])
  elsif [:has_many, :has_one].include?(reflection[:macro])
    assoc_select.push(reflection[:foreign_key])
  else
    fail Datasource::Error, "unsupported association type #{reflection[:macro]} - TODO"
  end
end

Instance Method Details

#attribute_exposed?(name) ⇒ Boolean



153
154
155
# File 'lib/datasource/base.rb', line 153

def attribute_exposed?(name)
  @expose_attributes.include?(name.to_s)
end

#get_select_valuesObject



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/datasource/base.rb', line 119

def get_select_values
  scope_table = adapter.primary_scope_table(self)
  select_values = Set.new
  select_values.add("#{scope_table}.#{primary_key}")

  self.class._attributes.values.each do |att|
    if attribute_exposed?(att[:name])
      if att[:klass] == nil
        select_values.add("#{scope_table}.#{att[:name]}")
      elsif att[:klass].ancestors.include?(Attributes::ComputedAttribute)
        att[:klass]._depends.keys.map(&:to_s).each do |name|
          next if name == scope_table
          next if name == "loaders"
          adapter.ensure_table_join!(self, name, att)
        end
        att[:klass]._depends.each_pair do |table, names|
          next if table.to_sym == :loaders
          Array(names).each do |name|
            select_values.add("#{table}.#{name}")
          end
          # TODO: handle depends on virtual attribute
        end
      elsif att[:klass].ancestors.include?(Attributes::QueryAttribute)
        select_values.add("(#{att[:klass].select_value}) as #{att[:name]}")
        att[:klass]._depends.each do |name|
          next if name == scope_table
          adapter.ensure_table_join!(self, name, att)
        end
      end
    end
  end
  select_values.to_a
end

#primary_keyObject



84
85
86
# File 'lib/datasource/base.rb', line 84

def primary_key
  :id
end

#results(rows = nil) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/datasource/base.rb', line 157

def results(rows = nil)
  rows ||= adapter.get_rows(self)

  @expose_attributes.each do |name|
    att = self.class._attributes[name]
    fail Datasource::Error, "attribute #{name} doesn't exist for #{self.class.orm_klass.name}, did you forget to call \"computed :#{name}, :db_column_dependency\" in your datasource_module? See https://github.com/mrbrdo/datasource#model-methods--virtual-attributes" unless att
    klass = att[:klass]
    next unless klass

    next if rows.empty?

    if att[:klass].ancestors.include?(Attributes::ComputedAttribute)
      loaders = att[:klass]._depends[:loaders]
      if loaders
        Array(loaders).each do |name|
          if loader = self.class._loaders[name]
            if loaded_values = loader.load(rows.map(&primary_key), rows, @scope)
              unless rows.first.loaded_values
                rows.each do |row|
                  row.loaded_values = {}
                end
              end
              rows.each do |row|
                row.loaded_values[name] = loaded_values[row.send(primary_key)] || loader.default_value
              end
            end
          else
            raise Datasource::Error, "loader with name :#{name} could not be found"
          end
        end
      end
    end
  end

  rows
end

#select(*names) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/datasource/base.rb', line 92

def select(*names)
  failure = ->(name) { fail Datasource::Error, "attribute or association #{name} doesn't exist for #{self.class.orm_klass.name}, did you forget to call \"computed :#{name}, <dependencies>\" in your datasource_module?" }
  names.each do |name|
    if name.kind_of?(Hash)
      name.each_pair do |assoc_name, assoc_select|
        assoc_name = assoc_name.to_s
        if self.class._associations.key?(assoc_name)
          @expose_associations[assoc_name] ||= []
          @expose_associations[assoc_name] += Array(assoc_select)
          @expose_associations[assoc_name].uniq!
        else
          failure.call(assoc_name)
        end
      end
    else
      name = name.to_s
      if self.class._attributes.key?(name)
        @expose_attributes.push(name)
      else
        failure.call(name)
      end
    end
  end
  @expose_attributes.uniq!
  self
end

#select_allObject



88
89
90
# File 'lib/datasource/base.rb', line 88

def select_all
  @expose_attributes = self.class._attributes.keys.dup
end