首页
/ Canard 项目技术文档

Canard 项目技术文档

2024-12-27 18:51:37作者:温艾琴Wonderful

1. 安装指南

Rails 3.x, 4.x & 5.x

  1. 将 Canard gem 添加到你的 Gemfile 中:

    gem "canard"
    
  2. 为用户表添加 roles_mask 字段:

    rails g migration add_roles_mask_to_users roles_mask:integer
    rake db:migrate
    

完成以上步骤后,安装就完成了!

Rails 2.x

很抱歉,Canard 仅支持 Rails 3 及以上版本。

支持的 ORM

Canard 是 ORM 无关的。目前实现了 ActiveRecord 和 Mongoid 的适配器。新的适配器可以轻松添加,但需要确认 CanCan 是否也支持你的适配器。

2. 项目的使用说明

Canard 结合了 CanCan 和 RoleModel,使得在 Rails 中实现基于角色的权限控制变得简单。Canard 为模型的能力定义提供了自己的文件夹和结构。使用 Canard 生成器是最简单的开始方式。

以下是如何定义具有 :admin 和 :manager 角色的 User 模型:

class User < ActiveRecord::Base
  acts_as_user :roles => [:manager, :admin]
end

如果用户同时具有 :manager 和 :admin 角色,Canard 会首先查找用户的能力定义,然后按定义的顺序查找其他角色。

3. 项目 API 使用文档

以下是 Canard 生成器的基本使用方法:

rails g canard:ability 用户 can:[read,create]:[账户,报表] cannot:destroy:账户

这将生成一个能力文件夹和相关的 spec 文件。

生成的 app/abilities/users.rb 文件可能看起来像这样:

Canard::Abilities.for(:用户) do
  can [:read, :create], 账户
  cannot [:destroy], 账户
  can [:read, :create], 报表
end

相关的测试文件 spec/abilities/users_spec.rb 可能看起来像这样:

require_relative '../spec_helper'
require "cancan/matchers"

describe Ability, "for :用户" do
  before do
    @用户 = Factory.create(:用户)
  end

  subject { Ability.new(@用户) }

  describe 'on 账户' do
    before do
      @账户 = Factory.create(:账户)
    end

    it { should be_able_to(:read, @账户) }
    it { should be_able_to(:create, @账户) }
    it { should_not be_able_to(:destroy, @账户) }
  end

  describe 'on 报表' do
    before do
      @报表 = Factory.create(:报表)
    end

    it { should be_able_to(:read, @报表) }
    it { should be_able_to(:create, @报表) }
  end
end

4. 项目安装方式

请遵循以下步骤安装 Canard:

  1. 添加 Canard gem 到你的 Gemfile。
  2. 运行 bundle install 来安装 gem。
  3. 使用上述提到的命令生成能力定义和 spec 文件。
  4. 根据生成的文件自定义能力定义。
  5. 运行测试来确保一切正常工作。

以上就是 Canard 的安装和使用说明,希望对您有所帮助。

登录后查看全文
热门项目推荐