Skip to content

Instantly share code, notes, and snippets.

@dmke
Forked from coorasse/main.rb
Last active August 23, 2021 10:50
Show Gist options
  • Save dmke/937a7d0323a6b5907c178da103df850f to your computer and use it in GitHub Desktop.
Save dmke/937a7d0323a6b5907c178da103df850f to your computer and use it in GitHub Desktop.
CanCanCan Issue
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile do
source "https://rubygems.org"
gem "rails", "6.1.4.1"
gem "cancancan"
gem "sqlite3"
end
require "active_record"
require "cancancan"
require "cancan/model_adapters/conditions_extractor"
require "cancan/model_adapters/conditions_normalizer"
require "cancan/model_adapters/sti_normalizer"
require "cancan/model_adapters/active_record_adapter"
require "cancan/model_adapters/active_record_4_adapter"
require "cancan/model_adapters/active_record_5_adapter"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
# create your tables here
ActiveRecord::Schema.define do
create_table :customers, force: true do |t|
t.string :name
end
create_table :users, force: true do |t|
t.string :name
end
create_join_table :customers, :users, force: true
end
class Customer < ActiveRecord::Base
end
class User < ActiveRecord::Base
has_and_belongs_to_many :customers
end
class Ability
include CanCan::Ability
class ViaIDs < Ability
def initialize(user)
can :manage, Customer, id: user.customer_ids
end
end
class ViaSelect < Ability
def initialize(user)
can :manage, Customer, id: user.customers.select(:id)
end
end
end
class BugTest < Minitest::Test
def setup
@customers = ["UPS", "DHL", "FedEx"].map { |name|
Customer.create! name: name
}
@other_customer = Customer.create! name: "Other"
@user = User.create!(name: "manager").tap { |user|
user.customers << @customers
}
end
def test_via_ids
verify_abilities Ability::ViaIDs.new(@user)
end
def test_via_select
verify_abilities Ability::ViaSelect.new(@user)
end
private
def verify_abilities(ability)
customers = Customer.accessible_by(ability, :read).count
assert_equal @customers.size, customers
assert ability.can?(:read, @customers[0])
assert ability.cannot?(:read, @other_customer)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment