将模型的作用范围推向表面。
Periscope provides a simple way to chain scopes on your models and to open those scopes up to your users.
Periscope sits on top of your favorite ORM. Currently, the following ORMs are supported through individual gems extending Periscope:
Simply add the gem to your bundle and you're off!
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:
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)
endYou can imagine how bad this would get if more than two scopes were involved.
With Periscope, you can have this instead:
def index
@articles = Article.periscope(request.query_parameters)
endThe 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.
"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.
class User = ?", s) }
scope_accessible :gender
endAnd in your controller:
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
endHow can I make it better?
暂无开放 Issues,或尚未同步最近议题。