百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
P

periscope

> 编程语言
开源

将模型的作用范围推向表面。

270 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

将模型的作用范围推向表面。

Periscope

Periscope provides a simple way to chain scopes on your models and to open those scopes up to your users.

Installation

Periscope sits on top of your favorite ORM. Currently, the following ORMs are supported through individual gems extending Periscope:

  • Active Record (periscope-activerecord)
  • MongoMapper (periscope-mongo_mapper)
  • Mongoid (periscope-mongoid)
  • DataMapper (periscope-data_mapper)

Simply add the gem to your bundle and you're off!

The Problem

More often than not, the index action in a RESTful Rails controller is expected to do a lot more than simply return all the records for a given model. We ask it to do all sorts of stuff like filtering, sorting and paginating results. Of course, this is typically done using scopes.

But it can get ugly building long, complicated chains of scopes in the controller, especially when you try to give your users control over the scoping. Picture this:

ruby
def index
  @articles = Article.scoped
  @articles = @articles.published_after(params[:published_after]) if params.key?(:published_after)
  @articles = @articles.published_before(params[:published_before]) if params.key?(:published_before)
end

You can imagine how bad this would get if more than two scopes were involved.

The Solution

With Periscope, you can have this instead:

ruby
def index
  @articles = Article.periscope(request.query_parameters)
end

The periscope method will find keys in your params matching your scope names and chain your scopes for you.

Note: We're using request.query_parameters so that we can exclude our controller and action params. request.query_parameters will just return the params that appear in the query string.

But Wait!

"What if I don't want to make all my scopes publicly accessible?"

Within your model you can use the scope_accessible method to specify which scopes you want Periscope to honor.

ruby
class User = ?", s) }

  scope_accessible :gender
end

And in your controller:

ruby
class UsersController  true` option. Whenever the received parameter is truthy, the scope will be applied. Otherwise, it will be skipped.

```ruby
class User = ?", date)
  end

  def self.ends_before(date)
    where("ends_at = ?", date)
  end

  def self.end_date(date)
    where("ends_at <= ?", date)
  end
end

This sucks.

How can I make it better?

  1. Fork it.
  2. Make it better.
  3. Send me a pull request.

Issues· 2 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言