Skip to content

Instantly share code, notes, and snippets.

@travisofthenorth
Created October 7, 2018 23:13
Show Gist options
  • Save travisofthenorth/eb2a68f5cd309dc7442ec4e1e55ae117 to your computer and use it in GitHub Desktop.
Save travisofthenorth/eb2a68f5cd309dc7442ec4e1e55ae117 to your computer and use it in GitHub Desktop.
Intersection use case - authorize a user who has an allowed role/ability
class PaymentsController < AuthenticatedController
before_action { authorize!(roles: [:superuser], abilities: [:charge_user, :manage_payments]) }
end
class AuthenticatedController < ApplicationController
def authorize!(roles: [], abilities: [])
# current
(roles & current_user.roles).any? || (abilities & current_user.abilities).any?
# desired
roles.intersect?(current_user.roles) || abilities.intersect?(current_user.abilities)
end
end
@travisofthenorth
Copy link
Author

travisofthenorth commented Oct 7, 2018

The current behavior creates an intermediate array for both intersection tests when the resulting array is clearly not needed.

With the desired behavior, we could avoid creating the intermediate array and produce a faster best case runtime.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment