Class: Card::Query::RefSpec

Inherits:
Spec show all
Defined in:
lib/card/query/ref_spec.rb

Constant Summary collapse

REFERENCE_DEFINITIONS =
{
  :refer_to => [ :out      ],   :referred_to_by => [ :in      ],
  :link_to  => [ :out, 'L' ],   :linked_to_by   => [ :in, 'L' ],
  :include  => [ :out, 'I' ],   :included_by    => [ :in, 'I' ]
}
REFERENCE_FIELDS =
{
  :out => [ :referer_id, :referee_id ],
  :in  => [ :referee_id, :referer_id ]
}

Instance Attribute Summary

Attributes inherited from Spec

#spec

Instance Method Summary collapse

Methods inherited from Spec

#cast_type, #match_prep, #quote, #safe_sql

Constructor Details

#initialize(key, val, parent) ⇒ RefSpec

Returns a new instance of RefSpec.



14
15
16
# File 'lib/card/query/ref_spec.rb', line 14

def initialize key, val, parent
  @key, @val, @parent = key, val, parent
end

Instance Method Details

#to_sql(*args) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/card/query/ref_spec.rb', line 18

def to_sql *args
  dir, type = REFERENCE_DEFINITIONS[ @key.to_sym ]
  field1, field2 = REFERENCE_FIELDS[ dir ]
  cond = type ? ["ref_type='#{type}'"] : []

  sql =  %[select #{field1} as ref_id from card_references]
  if @val == '_none'
    cond << "present = 0"
  else
    cardspec = CardSpec.build(:return=>'id', :_parent=>@parent).merge(@val)
    sql << %[ join #{ cardspec.to_sql } as c on #{field2} = c.id]
  end
  sql << %[ where #{ cond * ' and ' }] if cond.any?
  
  "(#{sql})"
end