Skip to content

Commit 38b5884

Browse files
committed
Extract User#parsed_roles method
I'm planning to introduce another role-related predicate method in a subsequent commit. Extracting this method first will make that change easier. I'm pretty convinced the call to `#to_s` was made redundant when the safe navigation operator was introduced in this commit [1]. However, I suppose it's theoretically possible for the parsed JSON returned from `HydraPublicApiClient.fetch_oauth_user` via `User.from_token` to contain non-String values, so I'm going to leave it in place for now. [1]: 9a1fdb1
1 parent b4bd337 commit 38b5884

File tree

2 files changed

+27
-11
lines changed

2 files changed

+27
-11
lines changed

app/models/user.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,11 @@ def student?
5151
end
5252

5353
def admin?
54-
(roles&.to_s&.split(',')&.map(&:strip) || []).include?('editor-admin')
54+
parsed_roles.include?('editor-admin')
55+
end
56+
57+
def parsed_roles
58+
roles&.to_s&.split(',')&.map(&:strip) || []
5559
end
5660

5761
def ==(other)

spec/models/user_spec.rb

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -277,24 +277,36 @@
277277
end
278278
end
279279

280-
describe '#admin?' do
281-
it 'returns true if the user has the editor-admin role in Hydra' do
282-
user = build(:user, roles: 'editor-admin')
283-
expect(user).to be_admin
280+
describe '#parsed_roles' do
281+
it 'returns array of role names when roles is set to comma-separated string' do
282+
user = build(:user, roles: 'role-1,role-2')
283+
expect(user.parsed_roles).to eq(%w[role-1 role-2])
284284
end
285285

286-
it 'returns false if the user does not have the editor-admin role in Hydra' do
287-
user = build(:user, roles: 'another-editor-admin')
288-
expect(user).not_to be_admin
286+
it 'strips leading & trailing spaces from role names' do
287+
user = build(:user, roles: ' role-1 , role-2 ')
288+
expect(user.parsed_roles).to eq(%w[role-1 role-2])
289289
end
290290

291-
it 'returns false if roles are empty in Hydra' do
291+
it 'returns empty array when roles is set to empty string' do
292292
user = build(:user, roles: '')
293-
expect(user).not_to be_admin
293+
expect(user.parsed_roles).to eq([])
294294
end
295295

296-
it 'returns false if roles are nil in Hydra' do
296+
it 'returns empty array when roles is set to nil' do
297297
user = build(:user, roles: nil)
298+
expect(user.parsed_roles).to eq([])
299+
end
300+
end
301+
302+
describe '#admin?' do
303+
it 'returns true if the user has the editor-admin role in Hydra' do
304+
user = build(:user, roles: 'editor-admin')
305+
expect(user).to be_admin
306+
end
307+
308+
it 'returns false if the user does not have the editor-admin role in Hydra' do
309+
user = build(:user, roles: 'another-editor-admin')
298310
expect(user).not_to be_admin
299311
end
300312
end

0 commit comments

Comments
 (0)