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
84
85
86
|
# File 'lib/grouped_model.rb', line 12
def has_groups(options={})
return if has_groups?
class_eval {
include GroupedModel::GroupedInstanceMethods
def self.has_groups?
true
end
def self.visible
visible_to(nil)
end
unless instance_methods.include? 'visible_to?'
def visible_to?(reader)
return true
end
end
alias_method_chain :visible_to?, :groups
}
has_many :permissions, :as => :permitted
has_many :groups, :through => :permissions
Group.define_retrieval_methods(self.to_s)
named_scope :visible_to, lambda { |reader|
if reader.nil? || reader.groups.empty?
conditions = "pp.group_id IS NULL"
else
ids = reader.group_ids
conditions = reader.nil? ? "pp.group_id IS NULL" : ["pp.group_id IS NULL OR pp.group_id IN(#{ids.map{"?"}.join(',')})", *ids]
end
{
:joins => "LEFT OUTER JOIN permissions as pp on pp.permitted_id = #{self.table_name}.id AND pp.permitted_type = '#{self.to_s}'",
:group => column_names.map { |n| self.table_name + '.' + n }.join(','),
:conditions => conditions,
:readonly => false
}
}
named_scope :ungrouped, {
:select => "#{self.table_name}.*, count(pp.id) as group_count",
:joins => "LEFT OUTER JOIN permissions as pp on pp.permitted_id = #{self.table_name}.id AND pp.permitted_type = '#{self.to_s}'",
:having => "group_count = 0",
:group => column_names.map { |n| self.table_name + '.' + n }.join(','), :readonly => false
} do
def count
length
end
end
named_scope :grouped, {
:select => "#{self.table_name}.*, count(pp.id) as group_count",
:joins => "LEFT OUTER JOIN permissions as pp on pp.permitted_id = #{self.table_name}.id AND pp.permitted_type = '#{self.to_s}'",
:having => "group_count > 0",
:group => column_names.map { |n| self.table_name + '.' + n }.join(','),
:readonly => false
} do
def count
length
end
end
named_scope :belonging_to, lambda { |group|
{
:joins => "INNER JOIN permissions as pp on pp.permitted_id = #{self.table_name}.id AND pp.permitted_type = '#{self.to_s}'",
:group => column_names.map { |n| self.table_name + '.' + n }.join(','),
:conditions => ["pp.group_id = ?)", group.id],
:readonly => false
}
}
end
|