> For the complete documentation index, see [llms.txt](https://clear.gitbook.io/project/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://clear.gitbook.io/project/querying/the-collection-object/scopes.md).

# Scopes

Scope provides elegant way to write commonly used query fragments and improve readability of your code. Scope returns a new collection Collection or taint the current Collection.

Let's get an example:

```ruby
class User
    include Clear::Model

    primary_key

    column role : String
    column role_level : Int32
    column email : String
    column active : Bool

    scope :with_privileges do |level|
        where{ role.in?(%w(superadmin admin)) | (role_level > level) }
    end
    scope(:active){ where(active: true) }
end

# Later one:
User.with_privileges(3).each do |x|
    puts "Admin #{x.id} - #{x.email}"
end
```

Scope can be easily chained and you can pass argument to them too:

```ruby
User.with_admin_privileges(4).active
```

Scope live both in `Model::Collection` and `Model` code space, meaning you may ignore `Model.query` to start a new Collection but instead go straight to `Model.scope`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://clear.gitbook.io/project/querying/the-collection-object/scopes.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
