Class: Card::Query::Value

Inherits:
Object show all
Includes:
Clause
Defined in:
lib/card/query/value.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Clause

#match_prep, #quote, #safe_sql

Constructor Details

#initialize(rawvalue, query) ⇒ Value

Returns a new instance of Value.



8
9
10
11
12
# File 'lib/card/query/value.rb', line 8

def initialize rawvalue, query
  @query = query
  @operator, @value = parse_value rawvalue
  canonicalize_operator
end

Instance Attribute Details

#operatorObject (readonly)

Returns the value of attribute operator.



6
7
8
# File 'lib/card/query/value.rb', line 6

def operator
  @operator
end

#queryObject (readonly)

Returns the value of attribute query.



6
7
8
# File 'lib/card/query/value.rb', line 6

def query
  @query
end

#valueObject (readonly)

Returns the value of attribute value.



6
7
8
# File 'lib/card/query/value.rb', line 6

def value
  @value
end

Instance Method Details

#canonicalize_operatorObject



22
23
24
25
26
27
28
# File 'lib/card/query/value.rb', line 22

def canonicalize_operator
  if target = OPERATORS[@operator.to_s]
    @operator = target
  else
    raise BadQuery, "Invalid Operator #{@operator}"
  end
end

#parse_value(rawvalue) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/card/query/value.rb', line 14

def parse_value rawvalue
  case rawvalue
  when String, Integer then ['=', rawvalue]
  when Array           then [rawvalue[0], rawvalue[1..-1]]
  else raise("Invalid Condition Clause #{rawvalue}.inspect}")
  end
end

#sqlize(v) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/card/query/value.rb', line 30

def sqlize v
  case v
  when Query then  v.to_sql
  when Array then  '(' + v.flatten.map { |x| sqlize(x) }.join(',') + ')'
  else quote(v.to_s)
  end
end

#to_sql(field) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/card/query/value.rb', line 38

def to_sql field
  op = @operator
  v = @value
  table = @query.table_alias

  field, v = case field.to_s
             when 'name'
               ["#{table}.key", [v].flatten.map(&:to_name).map(&:key)]
             when 'content'
               ["#{table}.db_content", v]
             else
               ["#{table}.#{safe_sql field}", v]
    end

  v = v[0] if Array === v && v.length == 1 && op != 'in'
  if op == '~'
    cxn, v = match_prep(v)
    %(#{field} #{cxn.match(sqlize(v))})
  else
    "#{field} #{op} #{sqlize(v)}"
  end
end