Skip to content

Commit 5205f51

Browse files
authored
Introduce helpful scopes (#538)
Introduce a couple of helpful scopes to ExternalUser and Group - **Introduce members_of scope** - **Introduce active scope to users and groups**
1 parent c275ea9 commit 5205f51

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

audiences/app/models/audiences/external_user.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ class ExternalUser < ApplicationRecord
2525
Audiences::Notifications.publish(*[*contexts, *group_contexts, *match_all_contexts].uniq)
2626
end
2727

28+
scope :active, -> { where(active: true) }
29+
30+
scope :members_of, ->(*groups) do
31+
where(id: Audiences::GroupMembership.where(group_id: groups.pluck(:id)).select(:external_user_id))
32+
end
33+
2834
scope :search, ->(display_name) do
2935
where(arel_table[:display_name].matches("%#{display_name}%"))
3036
end
@@ -41,7 +47,7 @@ class ExternalUser < ApplicationRecord
4147
.group_by(&:resource_type)
4248
.values
4349
.reduce(self) do |scope, groups|
44-
scope.where(id: Audiences::GroupMembership.where(group_id: groups.pluck(:id)).select(:external_user_id))
50+
scope.members_of(*groups)
4551
end
4652
end
4753

audiences/app/models/audiences/group.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ class Group < ApplicationRecord
99
validates :external_id, presence: true
1010
validates :scim_id, presence: true
1111

12+
scope :active, -> { where(active: true) }
13+
1214
scope :search, ->(display_name) do
1315
where(arel_table[:display_name].matches("%#{display_name}%"))
1416
end

audiences/lib/audiences/configuration.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ module Audiences
3333
# config.default_users_scope = -> { includes(:groups).merge(Audiences::Group.where(scim_id: ALLOWED_GROUPS)) }
3434
# end
3535
#
36-
# This configuration defaults to `-> { where(active: true) }`
36+
# This configuration defaults to `-> { active }`
3737
#
3838
config_accessor :default_users_scope do
39-
->(*) { where(active: true) }
39+
->(*) { active }
4040
end
4141

4242
# Defines a default scope for groups, so the groups that are part of an audience can
@@ -56,10 +56,10 @@ module Audiences
5656
# config.default_groups_scope = -> { where(scim_id: ALLOWED_GROUPS) }
5757
# end
5858
#
59-
# This configuration defaults to `-> { where(active: true) }`
59+
# This configuration defaults to `-> { active }`
6060
#
6161
config_accessor :default_groups_scope do
62-
->(*) { where(active: true) }
62+
->(*) { active }
6363
end
6464

6565
# These are the user attributes that will be exposed in the audiences endpoints.

0 commit comments

Comments
 (0)