Giter Site home page Giter Site logo

utility_scopes's Introduction

Utility Scopes

Summary

Utility scopes provides a collection of utilitarian named scopes for use with your
ActiveRecord models.

Utility scopes was originally announced here and has expanded in scope and functionality since then thanks to user contributions. See the
CHANGELOG for contribution details.

Utility scopes has the following dependencies:

  • activerecord >= 2.1.0
  • rspec >= 1.1.4 (for specs only, not runtime)

Installation

To install the utility_scopes gem run the following:

sudo gem install utility_scopes

And to enable the scopes in your project just require utility_scopes:

require ‘utility_scopes’

Rails

You can also specify the gem dependency if you’re running Rails 2.1 in your config/environment.rb file:

Rails::Initializer.run do |config|

  1. config.gem “utility_scopes”
    end

You don’t need to require 'utility_scopes' in this case as Rails will automatically require it.

Scopes

Most examples assume the following Article class:

class Article < ActiveRecord::Base has_many :comments # (assume each comment also has a :user) has_many :contributors belongs_to :author, :class_name => ‘User’ end

Named scopes are chainable by nature, meaning that the following is possible:

Article.with(:comments).without(1, 2, 3).ordered.limited(5)

Any exceptions to chainable scopes will be specified in their section below.

With (eager-loading)

The with scope let’s you eager load your model associations. So instead of having to invoke find(:all, :include => [:association1, :association2]) just pass these association names into
the with named scope:


  1. Get all articles and eager-load their comments, each comments’ user, article contributors
  2. and the article author.
    Article.with({ :comments => :user }, :contributors, :author)
  1. Get all articles and eager-load their comments
    Article.with(:comments)

Again, just pass in the same arguments into eager that you would pass in as the :include value to ActiveRecord::Base#find

Without

contributed by danielmorrison

without excludes the given records from the result set:

Article.without(1, 2, 3) # Get all articles whose id is NOT 1, 2 or 3 Article.without(@article) # Get all articles without the given one Article.without(@new_articles) # Get all non-new articles

Limited

limited lets you place a limit on the number of results returned. By default
the scope will limit the result set to 10 results if no argument is passed in:

Article.limited # Get the first 10 articles Article.without(1).limited(5) # Get the first 5 articles where id != 1

If you’re using will_paginate and don’t
pass an argument to the scope then the per_page value that is used by will_paginate
will be used:

Article.per_page #=> 20 Article.limited # Get the first 20 articles

If you would like to specify a different default value you can do so on a per class basis
using default_limit:


  1. Set the default limit to be 15
    class Article < ActiveRecord::Base
    default_limit 15
    end
Article.limited # Get the first 15 articles

Date

after lets you dynamically select every record for a column after a choosen date.

Article.after(:created_at, Date.parse(‘2008-10-10’)) Article.created_after(Date.parse(‘2008-10-10’)) # equivalent to previous line

before lets you dynamically select every records for a column after a choosen date.

Article.before(:created_at, Date.parse(‘2008-10-10’)) Article.created_before(Date.parse(‘2008-10-10’)) # equivalent to previous line

at and on lets you select every records for a column after a choosen date.

Article.on(:created_at, Date.parse(‘2008-10-10’)) Article.created_at(Date.parse(‘2008-10-10’)) # equivalent to previous line

Ordered

Note: the ordered scope cannot be chained with any other order clauses

ordered lets you dynamically specify the ordering of your result set. If no
arguments are given it will default to created_at DESC. (ordered is also
available as order_by and sort_by)

Article.ordered # Get all articles ordered by “created_at DESC” Article.ordered(:id) # Get all articles ordered by “id” Article.ordered(“rank ASC”) # Get all articles ordered by “rank ASC” Article.order_by(:id) # order_by and sort_by are alias to ordered Article.order_by([:id, :desc], :popularity) # can take a two-element array as parameter Article.sort_by(:id => :desc, :popularity => :asc) # can take a hash as parameter
  1. only available for jruby/ruby 1.9
    Article.order_by_id # can be set as a sentence

If you would like to specify a different default sort order you can do so on a per class basis
using ordered_by:


  1. Set the default order to be “published_at DESC
    class Article < ActiveRecord::Base
    ordered_by ‘published_at DESC
    end
Article.ordered # Get all articles ordered by “published_at DESC” Article.ordered(“rank ASC”) # Get all articles ordered by “rank ASC

The current default ordering for a class can always be accessed via default_ordering:

Article.default_ordering #=> “published_at DESC

PKs

only_pks selects only the primary key column. This is useful when combined with the pks class method to get the primary key values as an array:

Article.published.limited(10).only_pks # Get the first 10 published articles with only the ‘id’ value populated [, , …] Article.published.limited(10).pks # Get the first 10 published article ids: [1, 2, 3 …]

utility_scopes's People

Contributors

danielmorrison avatar jney avatar ptzn avatar rwdaigle avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar

Forkers

cliffrowley locum

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.