Class: MetaContent::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/meta_content/query.rb

Instance Method Summary collapse

Constructor Details

#initialize(record) ⇒ Query

Returns a new instance of Query.



4
5
6
# File 'lib/meta_content/query.rb', line 4

def initialize(record)
  @record = record
end

Instance Method Details

#delete_all(deletes) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/meta_content/query.rb', line 34

def delete_all(deletes)
  deletes.each do |namespace, keys|
    next unless keys.any?
    key_clause = keys.map{|k| h(k) }.join(',')
    sql = "DELETE FROM #{qtn} WHERE #{qtn}.object_id = #{h(pk)} AND #{qtn}.namespace = #{h(namespace)} AND #{qtn}.lookup IN (#{key_clause})"
    execute(sql)
  end
end

#h(val) ⇒ Object



8
9
10
# File 'lib/meta_content/query.rb', line 8

def h(val)
  ActiveRecord::Base.sanitize(val)
end

#select_allObject



12
13
14
15
16
17
18
19
20
# File 'lib/meta_content/query.rb', line 12

def select_all
  sql = "SELECT #{qtn}.namespace, #{qtn}.lookup, #{qtn}.value, #{qtn}.int_value FROM #{qtn} WHERE #{qtn}.object_id = #{h(pk)}"
  results = {}
  execute(sql).each do |row|
    results[row[0]] ||= {}
    results[row[0]][row[1]] = row[2]
  end
  results
end

#update_all(changes) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/meta_content/query.rb', line 22

def update_all(changes)
  sql = "INSERT INTO #{qtn}(namespace,object_id,lookup,value,int_value) VALUES "
  values = changes.map do |namespace, namespaced_changes|
    namespaced_changes.map do |k, change|
      "(#{h(namespace)},#{h(pk)},#{h(k)},#{h(change.value)},#{h(change.int_value)})"
    end
  end.flatten
  sql << values.join(',')
  sql << " ON DUPLICATE KEY UPDATE value = VALUES(value), int_value = VALUES(int_value)"
  execute(sql) if values.any?
end