Well the obvious way I think would be to simply parse the whole roles array:
roles = [
"id=Accountant,id=TOTO,id=client",
"id=Admin,id=YOYO,id=custom",
"id=CDI,id=SC"
]
user_roles = roles.join(',').split(',').map { |r| r.split('=', 2).last.downcase }
Where user_roles becomes:
["accountant", "toto", "client", "admin", "yoyo", "custom", "cdi", "sc"]
Now you can simply do something like:
user_roles.include?('admin')
Or to find any of the "admin", "national", "local" occurences:
# array1 AND array2, finds the elements that occur in both:
> %w(admin national local) & user_roles
=> ["admin"]
Or perhaps to just find out if the user has any of those roles:
# When there are no matching elements, it will return an empty array
> (%w(admin national local) & user_roles).empty?
=> false
> (["megaboss", "superadmin"] & user_roles).empty?
=> true
And here it is in a more complete example with constants and methods and all!
SUPERVISOR_ROLES = %w(admin national local)
def is_supervisor?(roles)
!(SUPERVISOR_ROLES & roles).empty?
end
def parse_roles(raw_array)
raw_array.flat_map { |r| r.split(',').map { |r| r.split('=', 2).last.downcase } }
end
roles = [
"id=Accountant,id=TOTO,id=client",
"id=Admin,id=YOYO,id=custom",
"id=CDI,id=SC"
]
raise "you no boss :(" unless is_supervisor?(parse_roles(roles))
This of course may be inefficient if the data set is large, but a bit cleaner and maybe even safer than performing such a regex, for example someone could create a role called AdminHack which would still be matched by the /id=Admin/ regex and by writing such a general role parser may become useful along the way if you want to check for other roles for other purposes.
(And yes, obviously this solution creates a hefty amount of intermediary arrays and other insta-discarded objects and has plenty of room for optimization)
id=valuepairs. What's the expected result?role = 'admin' if roles.last = ...but I doubt that's what you're looking for here. What should the method return for the array you provided ?idbut the matched result forid=Admin. If it is matched, I have to return 'admin', ifid=custommatches, I have to assignuserto therolevariable.id={some role value}and assign the corresponding value to therolevariable.id=Adminandid=custom. The provided example code would setroleto'user'. Do you just want the last match?