No commit activity in last 3 years
No release in over 3 years
Make your queries prettier and more reusable by having a named scope for every find-parameter. As easy as Post.include(:author, :comments)
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

< 3.0.pre
>= 1.2.9
>= 1.3.0
 Project Readme

BasicNamedScopes¶ ↑

Basic named scopes for ActiveRecord. Propagates the parameters of the find-method as named scopes, for easy reusability and prettier code.

Instead of writing:

Post.all(:conditions => { :published => true }, :select => :title, :include => :author)

You can now write:

Post.conditions(:published => true).select(:title).with(:author)

All named scopes are called the same, except for include, which is now called with, because include is a reserved method.

Also, the scope conditions is aliased as where, just as in ActiveRecord 3.

Reuse them by making class methods:

class Post < ActiveRecord::Base

  def self.published
    conditions(:published => true)
  end

  def self.visible
    conditions(:visible => true)
  end

  def self.index
    published.visible
  end

end

Also, the all-method is a named scope now, so you can chain after callling all, for greater flexibility.

Post.all.published

Arrays can be used as multple parameters too, sparing you some brackets.

Post.with(:author, :comments).conditions("name LIKE ?", query)

The read_only and lock scopes default to true, but can be adjusted.

Post.readonly         # => same as Post.all(:readonly => true)
Post.readonly(false)  # => same as Post.all(:readonly => false)

Why?¶ ↑

NamedScopes are really handy and they should play a more central theme in ActiveRecord. While I heard that ActiveRecord 3 will support similar syntax, there is no reason to wait any longer.

I find defining named scopes very ugly, especially when dealing with parameters. Just compare the amount of curly braces!

# Using normal named scope:
named_scope :name_like, lambda { |query| { :conditions => ["name LIKE ?", query] } }

# Using BasicNamedScopes
def self.name_like(query)
  conditions("name LIKE ?", query)
end

Also, regular named scopes don’t support using other named scopes at all!

I found myself implementing (mostly conditions, but others too) so often, that a little gem like this would be the obvious choice. Use it if a gem like searchlogic is overkill for your needs.

Installing¶ ↑

The gem is called “basic_named_scopes”. You know how to install it.

gem install basic_named_scopes

Use it in Rails:

config.gem "basic_named_scopes"

Copyright © 2009 Iain Hecker. Released under the MIT License.