Skip to content

Instantly share code, notes, and snippets.

@daniloisr
Created July 30, 2021 20:18
Show Gist options
  • Save daniloisr/0a179e694d2eead7341b11749d3caba9 to your computer and use it in GitHub Desktop.
Save daniloisr/0a179e694d2eead7341b11749d3caba9 to your computer and use it in GitHub Desktop.
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'activerecord', '~> 6.0'
gem 'sqlite3'
end
require 'pp'
require 'active_record'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
class CreatePermissionMigration < ActiveRecord::Migration[6.0]
def self.version; 1; end
def change; create_table :permissions { |t| t.integer :level }; end
end
CreatePermissionMigration.migrate(:up)
ALL = 1 << 0
OWNED_BY = 1 << 1
SALESPERSOM = 1 << 2
LEAD_ATTORNEY = 1 << 3
ORIGINATING_ATTORNEY = 1 << 4
ASSIGNED_STAFF = 1 << 5
class Permission < ActiveRecord::Base
end
permission1 = Permission.create(level: SALESPERSOM | ASSIGNED_STAFF)
permission2 = Permission.create(level: LEAD_ATTORNEY | ASSIGNED_STAFF)
permission3 = Permission.create(level: ASSIGNED_STAFF)
# use "&" for include any
pp Permission.where('level & ? > 0', SALESPERSOM).pluck(:id) == [permission1.id]
pp Permission.where('level & ? > 0', LEAD_ATTORNEY).pluck(:id) == [permission2.id]
pp Permission.where('level & ? > 0', ASSIGNED_STAFF).pluck(:id) == [permission1.id, permission2.id, permission3.id]
# use "=" for matching all
pp Permission.where('level = ?', ASSIGNED_STAFF).pluck(:id) == [permission3.id]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment