Class: Netzke::Basepack::DataAdapters::ActiveRecordAdapter

Inherits:
AbstractAdapter
  • Object
show all
Defined in:
lib/netzke/basepack/data_adapters/active_record_adapter.rb

Overview

Implementation of AbstractAdapter

Instance Attribute Summary

Attributes inherited from AbstractAdapter

#model

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AbstractAdapter

adapter_class, #assoc_values, #association_attr?, #errors_array, #find_record_children, #find_root_records, #first, #get_property_type, inherited, #initialize, #map_type, #model_respond_to?, #primary_key_attr?, #root, #save_record

Constructor Details

This class inherits a constructor from Netzke::Basepack::DataAdapters::AbstractAdapter

Class Method Details

.for_class?(model) ⇒ Boolean

Returns:

  • (Boolean)


4
5
6
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 4

def self.for_class?(model)
  model && model <= ActiveRecord::Base
end

Instance Method Details

#attr_type(attr_name) ⇒ Object



37
38
39
40
41
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 37

def attr_type(attr_name)
  method, assoc = method_and_assoc(attr_name)
  klass = assoc.nil? ? @model : assoc.klass
  klass.columns_hash[method].try(:type) || :string
end

#attribute_namesObject



33
34
35
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 33

def attribute_names
  @model.column_names
end

#class_for(assoc_name) ⇒ Object

Returns the model class for association columns



129
130
131
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 129

def class_for assoc_name
  @model.reflect_on_association(assoc_name.to_sym).klass
end

#combo_data(attr, query = "") ⇒ Object



85
86
87
88
89
90
91
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/netzke/basepack/data_adapters/active_record_adapter.rb', line 85

def combo_data(attr, query = "")
  method, assoc = method_and_assoc(attr[:name])

  if assoc
    # Options for an asssociation attribute

    relation = assoc.klass.all

    relation = extend_relation_with_scope(relation, attr[:scope])

    if attr[:filter_association_with]
      relation = attr[:filter_association_with].call(relation, query).to_a
      if attr[:getter]
        relation.map{ |r| [r.id, attr[:getter].call(r)] }
      else
        relation.map{ |r| [r.id, r.send(method)] }
      end
    elsif assoc.klass.column_names.include?(method)
      # apply query
      assoc_arel_table = assoc.klass.arel_table

      relation = relation.where(assoc_arel_table[method].matches("%#{query}%"))  if query.present?
      relation.to_a.map{ |r| [r.id, r.send(method)] }
    else
      query.downcase!
      # an expensive search!
      relation.to_a.map{ |r| [r.id, r.send(method)] }.select{ |id,value| value.to_s.downcase.include?(query) }
    end

  else
    distinct_combo_values(attr, query)
  end
end

#count_records(params, columns = []) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 54

def count_records(params, columns=[])
  # if get_relation was called before (e.g. through get_records), don't call it again, just use its latest result
  relation = @relation || get_relation(params)

  # addressing the n+1 query problem
  columns.each do |c|
    assoc, method = c[:name].split('__')
    relation = relation.includes(assoc.to_sym).references(assoc.to_sym) if method
  end

  relation.count
end

#destroy(ids) ⇒ Object



133
134
135
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 133

def destroy(ids)
  @model.destroy(ids)
end

#distinct_combo_values(attr, query) ⇒ Object



119
120
121
122
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 119

def distinct_combo_values(attr, query)
  records = query.empty? ? @model.find_by_sql("select distinct #{attr[:name]} from #{@model.table_name}") : @model.find_by_sql("select distinct #{attr[:name]} from #{@model.table_name} where #{attr[:name]} like '#{query}%'")
  records.map{|r| [r.send(attr[:name]), r.send(attr[:name])]}
end

#find_record(id, options = {}) ⇒ Object

Returns a record by id. Respects the following options:

  • scope - will only return a record if it falls into the provided scope



140
141
142
143
144
145
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 140

def find_record(id, options = {})
  # scope = options[:scope] || {}
  relation = @model.where(primary_key => id)
  relation = options[:scope].call(relation) if options[:scope].is_a?(Proc)
  relation.first
end

#foreign_key_for(assoc_name) ⇒ Object



124
125
126
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 124

def foreign_key_for assoc_name
  @model.reflect_on_association(assoc_name.to_sym).foreign_key
end

#get_assoc_property_type(assoc_name, prop_name) ⇒ Object



67
68
69
70
71
72
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 67

def get_assoc_property_type assoc_name, prop_name
  if prop_name && assoc = @model.reflect_on_association(assoc_name)
    assoc_column = assoc.klass.columns_hash[prop_name.to_s]
    assoc_column.try(:type)
  end
end

#get_records(params, columns = []) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 44

def get_records(params, columns=[])
  relation = get_relation(params)

  relation = fix_nplus1_problem(relation, columns)

  relation = apply_sorting(relation, columns, params[:sorters])

  relation = apply_offset(relation, params)
end

#get_relation(params = {}) ⇒ Object

An ActiveRecord::Relation instance encapsulating all the necessary conditions.



283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 283

def get_relation(params = {})
  relation = @model.all

  query = params[:query]

  if query.present?
    cannot_use_procs = query.size > 1

    and_predicates = query.map do |and_query|
      and_query.each do |q|
        if prok = q.delete(:proc)
          raise "Cannot use Proc conditions in OR queries" if cannot_use_procs
          relation = prok.call(relation, q[:value], q[:operator])
          and_query.delete(q)
        end
      end

      predicates_for_and_conditions(and_query)
    end

    # join them by OR
    predicates = and_predicates[1..-1].inject(and_predicates.first){ |r,c| r.or(c) }
    relation = relation.where(predicates)
  end

  if params[:filters]
    and_query = params[:filters]
    and_query.each do |q|
      relation = q[:proc].call(relation, q[:value], q[:operator]) if q[:proc]
    end

    and_query.delete_if{|q| q[:proc] }

    # apply other, non-Proc filters
    relation = relation.where(predicates_for_and_conditions(and_query))
  end

  relation = extend_relation_with_scope(relation, params[:scope])

  @relation = relation
end

#hash_fk_modelObject

Build a hash of foreign keys and the associated model



148
149
150
151
152
153
154
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 148

def hash_fk_model
  foreign_keys = {}
  @model.reflect_on_all_associations(:belongs_to).map{ |r|
    foreign_keys[r.association_foreign_key.to_sym] = r.name
  }
  foreign_keys
end

#human_attribute_name(name) ⇒ Object



186
187
188
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 186

def human_attribute_name(name)
  @model.human_attribute_name(name)
end

#method_and_assoc(attr_name) ⇒ Object

If association attribute is given, returns [method, association] Else returns [attr_name]



276
277
278
279
280
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 276

def method_and_assoc(attr_name)
  assoc_name, method = attr_name.to_s.split('__')
  assoc = @model.reflect_on_association(assoc_name.to_sym) if method
  assoc.nil? ? [attr_name] : [method, assoc]
end

#model_attributesObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 16

def model_attributes
  @model_attributes ||= attribute_names.map do |column_name|
    # If it's named as foreign key of some association, then it's an association column
    assoc = @model.reflect_on_all_associations.detect { |a| a.foreign_key == column_name }

    if assoc && !assoc.options[:polymorphic]
      candidates = %w{name title label} << assoc.klass.primary_key
      assoc_method = candidates.detect{|m| (assoc.klass.instance_methods.map(&:to_s) + assoc.klass.column_names).include?(m) }
      :#{assoc.name}__#{assoc_method}"
    else
      column_name.to_sym
    end
    # auto set up the default value from the column settings
    # c[:default_value] = @model.columns_hash[column_name].default if @model.columns_hash[column_name].default
  end
end

#move_records(params) ⇒ Object

FIXME



157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 157

def move_records(params)
  if defined?(ActsAsList) && @model.ancestors.include?(ActsAsList::InstanceMethods)
    ids = JSON.parse(params[:ids]).reverse
    ids.each_with_index do |id, i|
      r = @model.find(id)
      r.insert_at(params[:new_index].to_i + i + 1)
    end
    on_data_changed # copypaste nonsense
  else
    raise RuntimeError, "Model class should implement 'acts_as_list' to support reordering records"
  end
end

#new_record(params = {}) ⇒ Object



8
9
10
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 8

def new_record(params = {})
  @model.new(params)
end

#predicates_for_and_conditions(conditions) ⇒ Object



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 325

def predicates_for_and_conditions(conditions)
  return nil if conditions.empty?

  predicates = conditions.map do |q|
    q = HashWithIndifferentAccess.new(Netzke::Support.permit_hash_params(q))

    attr = q[:attr]
    method, assoc = method_and_assoc(attr)

    arel_table = assoc ? Arel::Table.new(assoc.klass.table_name.to_sym) : @model.arel_table

    value = q["value"]
    op = q["operator"]

    attr_type = attr_type(attr)

    case attr_type
    when :datetime
      update_predecate_for_datetime(arel_table[method], op, value.to_date)
    when :string, :text
      update_predecate_for_string(arel_table[method], op, value)
    when :boolean
      update_predecate_for_boolean(arel_table[method], op, value)
    when :date
      update_predecate_for_rest(arel_table[method], op, value.to_date)
    else
      update_predecate_for_rest(arel_table[method], op, value)
    end
  end

  # join them by AND
  predicates[1..-1].inject(predicates.first){ |r,p| r.and(p)  }
end

#primary_keyObject



12
13
14
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 12

def primary_key
  @model.primary_key.to_s
end

#record_to_array(r, attrs) ⇒ Object



170
171
172
173
174
175
176
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 170

def record_to_array(r, attrs)
  [].tap do |res|
    attrs.each do |a|
      res << record_value_for_attribute(r, a, a[:nested_attribute]) if a[:included] != false # :included ever used?..
    end
  end
end

#record_to_hash(r, attrs) ⇒ Object



178
179
180
181
182
183
184
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 178

def record_to_hash(r, attrs)
  {}.tap do |res|
    attrs.each do |a|
      res[a[:name].to_sym] = record_value_for_attribute(r, a, a[:nested_attribute]) if a[:included] != false
    end
  end
end

#record_value_for_attribute(r, a, through_association = false) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 190

def record_value_for_attribute(r, a, through_association = false)
  v = if association_attr?(a)
    split = a[:name].to_s.split(/\.|__/)
    assoc = @model.reflect_on_association(split.first.to_sym)
    if through_association
      split.inject(r) do |r, m| # Do we *really* need to descend deeper than 1 level?
        return nil if r.nil?

        # On the last iteration call the getter block
        if a[:getter] && split.last.equal?(m)
          a[:getter].call(r)
        elsif r.respond_to?(m)
          r.send(m)
        else
          logger.warn "Netzke: Wrong attribute name: #{a[:name]}" unless r.nil?
          nil
        end
      end
    else
      r.send("#{assoc.options[:foreign_key] || assoc.name.to_s.foreign_key}")
    end
  elsif a[:getter]
    a[:getter].call(r)
  elsif r.respond_to?("#{a[:name]}")
    r.send("#{a[:name]}")

  # the composite_primary_keys gem produces [Key1,Key2...] and [Value1,Value2...]
  # on primary_key and id requests. Basepack::AttrConfig converts the keys-array to an String.
  elsif primary_key.try(:to_s) == a[:name]
    r.id # return 'val1,val2...' on 'key1,key2...' composite_primary_keys
  end

  # a work-around for to_json not taking the current timezone into account when serializing ActiveSupport::TimeWithZone
  v = v.to_datetime.to_s(:db) if [ActiveSupport::TimeWithZone].include?(v.class)

  v
end

#set_record_value_for_attribute(record, attr, value) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 228

def set_record_value_for_attribute(record, attr, value)
  value = value.to_time_in_current_zone if value.is_a?(Date) # convert Date to Time
  unless attr[:read_only]
    if attr[:setter]
      attr[:setter].call(record, value)
    elsif record.respond_to?("#{attr[:name]}=")
      record.send("#{attr[:name]}=", value)
    elsif association_attr?(attr)
      split = attr[:name].to_s.split(/\.|__/)
      if attr[:nested_attribute]
        # We want:
        #     set_value_for_attribute({:name => :assoc_1__assoc_2__method, :nested_attribute => true}, 100)
        # =>
        #     record.assoc_1.assoc_2.method = 100
        split.inject(record) { |r,m| m == split.last ? (r && r.send("#{m}=", value) && r.save) : r.send(m) }
      else
        if split.size == 2
          # search for association and assign it to r
          assoc = @model.reflect_on_association(split.first.to_sym)
          assoc_method = split.last
          if assoc
            if assoc.macro == :has_one
              assoc_instance = record.send(assoc.name)
              if assoc_instance
                assoc_instance.send("#{assoc_method}=", value)
                assoc_instance.save # what should we do when this fails?..
              else
                # what should we do in this case?
              end
            else

              # set the foreign key to the passed value
              # not that if a negative value is passed, we reset the association (set it to nil)
              record.send("#{assoc.foreign_key}=", value.to_i < 0 ? nil : value)
            end
          else
            logger.warn "Netzke: Association #{assoc} is not known for class #{@model}"
          end
        else
          logger.warn "Netzke: Wrong attribute name: #{attr[:name]}"
        end
      end
    end
  end
end

#update_predecate_for_boolean(table, op, value) ⇒ Object



359
360
361
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 359

def update_predecate_for_boolean(table, op, value)
  table.eq(value)
end

#update_predecate_for_datetime(table, op, value) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 367

def update_predecate_for_datetime(table, op, value)
  case op
  when "eq"
    table.lteq(value.end_of_day).and(table.gteq(value.beginning_of_day))
  when "gt"
    table.gt(value.end_of_day)
  when "lt"
    table.lt(value.beginning_of_day)
  when "gteq"
    table.gteq(value.beginning_of_day)
  when "lteq"
    table.lteq(value.end_of_day)
  end
end

#update_predecate_for_rest(table, op, value) ⇒ Object



382
383
384
385
386
387
388
389
390
391
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 382

def update_predecate_for_rest(table, op, value)
  legal_ops = %w[eq gt lt gteq lteq]

  if legal_ops.include?(op.to_s)
    table.send(op, value)
  else
    logger.warn("Netzke: Illegal filter operator: #{op}")
    table
  end
end

#update_predecate_for_string(table, op, value) ⇒ Object



363
364
365
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 363

def update_predecate_for_string(table, op, value)
  table.matches "%#{value}%"
end

#virtual_attribute?(c) ⇒ Boolean

Returns:

  • (Boolean)


74
75
76
77
78
79
80
81
82
83
# File 'lib/netzke/basepack/data_adapters/active_record_adapter.rb', line 74

def virtual_attribute?(c)
  assoc_name, asso = c[:name].split('__')
  method, assoc = method_and_assoc(c[:name])

  if assoc
    return !assoc.klass.column_names.include?(method)
  else
    return !@model.column_names.include?(c[:name])
  end
end