Skip to content

Instantly share code, notes, and snippets.

@suratpyari
Created February 10, 2023 12:10
Show Gist options
  • Save suratpyari/5733d7fcd921fa61982b017567ddb1e0 to your computer and use it in GitHub Desktop.
Save suratpyari/5733d7fcd921fa61982b017567ddb1e0 to your computer and use it in GitHub Desktop.
find consolidated permissions
# # There are many users, many roles, and many modules in a system
# # - 1 User can have multipple roles
# # - 1 role can have permission to multiple module
# # The task is to simplify the data of user and roles into single JSON object
# # explanation :
# let roles = [
# {
# name: 'access-manager',
# modulePermsiion : {
# 'role_management' : ['read', 'write'],
# 'content_management' : ['update']
# # can have more module and their permission
# }
# },
# {
# name: 'content-manager',
# modulePermsiion : {
# 'content_management' : ['read', 'write']
# # can have more module and their permission
# }
# }
# ]
# let users = {
# name: 'meraj',
# roles: ['access-manager', 'content-manager']
# }
# # Write a program to take the above inputs and give a simplified output as given in below example
# let output = {
# name: 'meraj',
# modulePermsiion: {
# 'content_management' : ['read', 'write', 'update'],
# 'role_management' : ['read', 'write']
# }
# }
ROLES = [
{
:name=>"access-manager",
:modulePermsiion=>{:role_management=>["read", "write"], :content_management=>["update"]}
},
{
:name=>"content-manager",
:modulePermsiion=>{:content_management=>["read", "write"]}
}
]
def permissions(user)
users_permissions = ROLES.select{|r| user[:roles].include?(r[:name])}
.collect{|r| r[:modulePermsiion]}
.inject({}) do |result, element|
result.merge(element){|key, a_item, b_item| (a_item || [])+(b_item||[])}
end
{name: user[:name], modulePermsiion: users_permissions}
end
user = {:name=>"meraj", :roles=>["access-manager", "content-manager"]}
permissions(user)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment