Method: DataMapper::Persevere::Query#munge_condition

Defined in:
lib/persevere_adapter/query.rb

#munge_condition(condition) ⇒ Object

TODO: Clean this mess up.

Author:

  • lamb



8
9
10
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
# File 'lib/persevere_adapter/query.rb', line 8

def munge_condition(condition)
  loaded_value = condition.loaded_value
  return_value = ""
  subject = condition.subject 
  
  if subject.is_a?(DataMapper::Property)
    rhs = case loaded_value
    when String               then "\"#{loaded_value}\""
    when DateTime             then "date(%10.f)" % (Time.parse(loaded_value.to_s).to_f * 1000)
    when nil                  then "undefined"
    else                           loaded_value
    end
    return_value = "#{condition.subject.field}#{condition.__send__(:comparator_string)}#{rhs}"
  elsif subject.is_a?(DataMapper::Associations::ManyToOne::Relationship)
    # Join relationship, bury it down!
    if self.model != subject.child_model
      my_side_of_join = links.select{|relation| 
        relation.kind_of?(DataMapper::Associations::ManyToOne::Relationship) &&
        relation.child_model == subject.child_model &&
        # I would really like this to not look at the name, 
        # but sometimes they are different object of the same model
        relation.parent_model.name == self.model.name }.first
        
      # join_results = subject.child_model.all(subject.field.to_sym => loaded_value)
      join_results = subject.child_model.all(subject.child_key.first.name => loaded_value[subject.parent_key.first.name])
      
      return_value = join_results.map{|r| "#{self.model.key.first.name}=#{r[my_side_of_join.child_key.first.name]}"}.join('|')
    else
      comparator = loaded_value.nil? ? 'undefined' : loaded_value.key.first
      return_value = "#{subject.child_key.first.name}#{condition.__send__(:comparator_string)}#{comparator}"
    end
  elsif subject.is_a?(DataMapper::Associations::Relationship)
    if self.model != subject.child_model
      return_value = "#{subject.child_key.first.name}#{condition.__send__(:comparator_string)}#{loaded_value.key.first}"
    else
      comparator = loaded_value.nil? ? 'undefined' : loaded_value.key.first
      return_value = "#{subject.field}_id#{condition.__send__(:comparator_string)}#{comparator}"
    end
  end
  return_value
end