# 寻找 add\_api\_key\_scope 的用法示例

**URL:** https://meta.discourse.org/t/looking-for-usage-examples-of-add-api-key-scope/198939
**Category:** Development
**Tags:** rest-api
**Created:** [2021年八月2日 20:30 UTC](https://meta.discourse.org/t/looking-for-usage-examples-of-add-api-key-scope/198939 "2021-08-02T20:30:53Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![Hooksmith](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/hooksmith/32/142826_2.png) [@Hooksmith](https://meta.discourse.org/u/Hooksmith)
#### Post date: [2021年八月2日 20:30 UTC](https://meta.discourse.org/t/looking-for-usage-examples-of-add-api-key-scope/198939/1 "2021-08-02T20:30:53Z")

</div>

大家好，

我正在尝试使用 `Plugin::Instance` 上的这个方法：[discourse/lib/plugin/instance.rb at 06c60b017c86ddab489fd3d30c951c10b5c4d281 · ayampenyetan/discourse · GitHub](https://github.com/ayampenyetan/discourse/blob/06c60b017c86ddab489fd3d30c951c10b5c4d281/lib/plugin/instance.rb#L801-L803)

我尝试在 Discourse 代码库/GitHub 中搜索该方法的使用情况，但似乎除了测试用例之外，公开可访问的代码中并未实际使用该方法。

能否有人为我解释以下问题：

- 在插件中获取 `Plugin::Instance` 实例以调用该方法的正确方式是什么？
- 调用上述链接方法的正确时机是什么？如果我在插件中创建了一个新的端点，是否应该在创建端点之后调用此方法？它应该放在 `after_initialize` 之前还是内部？
- 以下代码似乎注册了作用域，但在尝试使用具有该作用域的管理员 API 密钥访问我注册的端点时，似乎无法找到该操作。当使用具有所有作用域的管理员 API 密钥访问该端点时，它能正常工作。为什么这不起作用？我在这里做错了什么？
- 我尝试在 actions 中添加一个 `urls` 条目，但似乎未被识别。如何成功地将作用域适用的 URL 列表添加到此结构中？

```ruby
after_initialize do

    module ::ApiKeyScopeTest
        class Engine < ::Rails::Engine
            engine_name "api_key_scope_test"
            isolate_namespace ApiKeyScopeTest
        end
    end

    class ApiKeyScopeTest::ApiKeyScopeTestController < ::ApplicationController

        def action
            ...
        end

    end

    ApiKeyScopeTest::Engine.routes.draw do
        post "/admin/plugins/api-key-scope-test" => "api_key_scope_test#action", constraints: AdminConstraint.new
    end

    Discourse::Application.routes.append do
        mount ::ApiKeyScopeTest::Engine, at: "/"
    end

    plugin = Plugin::Instance.new # 注意：尚不确定这是否正确

    plugin.add_api_key_scope(
        :test_scope,
        {
            post: {
                actions: %w[api_key_scope_test#action]
            }
        }
    )

end

```
