/
model_reflector.rb
83 lines (71 loc) · 2.06 KB
/
model_reflector.rb
1
2
3
4
5
6
7
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
module Shoulda
module Matchers
module ActiveRecord
module AssociationMatchers
# @private
class ModelReflector
delegate(
:associated_class,
:association_foreign_key,
:foreign_key,
:has_and_belongs_to_many_name,
:join_table_name,
:polymorphic?,
:validate_inverse_of_through_association!,
to: :reflection
)
delegate(
:through?,
to: :reflection,
allow_nil: true
)
def initialize(subject, name)
@subject = subject
@name = name
end
def association_relation
reflection.association_relation(subject)
end
def reflection
@reflection ||= reflect_on_association(name)
end
def reflect_on_association(name)
reflection = model_class.reflect_on_association(name)
if reflection
ModelReflection.new(reflection)
end
end
def model_class
subject.class
end
def build_relation_with_clause(name, value)
case name
when :conditions then associated_class.where(value)
when :order then associated_class.order(value)
else raise ArgumentError, "Unknown clause '#{name}'"
end
end
def extract_relation_clause_from(relation, name)
case name
when :conditions
relation.where_values_hash
when :order
relation.order_values.map { |value| value_as_sql(value) }.join(', ')
else
raise ArgumentError, "Unknown clause '#{name}'"
end
end
protected
attr_reader :subject, :name
def value_as_sql(value)
if value.respond_to?(:to_sql)
value.to_sql
else
value
end
end
end
end
end
end
end