`
xf986321
  • 浏览: 160923 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

something about with_scope

阅读更多

今天看了一点关于with_scope的知识,有点感觉,写点东西

with_scope 与 named_scope 没有关系,named_scope 是依赖于with_scope工作的。

1、with_scope

with_scope是给一个model添加一个scope来扩展功能

def self.all_male
  with_scope(:find => {:conditions => "gender = 'm'"}) do
    all_active
  end
end

def self.all_active
  with_scope(:find => {:conditions => "status = 'active'"}) do
    find(:first)
  end
end

# User.all_active
# SELECT * FROM "users" WHERE (status = 'active') LIMIT 1

# User.all_male
# SELECT * FROM "users" WHERE ((gender = 'm') AND (status = 'active')) LIMIT 1

 named_scope就是运用with_scope的这种特性来将多个name_scope形成一个query

2、学习编写自己的named_scope

module ActiveRecord
  module MynamedScope
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def mynamed_scope(name,options = {})
        puts "name is #{name}"
      end
    end

  end
end
ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope)


class User < ActiveRecord::Base
  mynamed_scope :active, :conditions => {:status =>  'active'}
  mynamed_scope :male, :conditions => {:gender => 'm'}
end

 我们就可以通过

 

User.active
User.male
User.active.male
User.male.active

 得到正确的返回结果。

最后结果

module ActiveRecord
  module MynamedScope
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods

      def myscopes
        read_inheritable_attribute(:myscopes) || write_inheritable_attribute(:myscopes, {})
      end

      def mynamed_scope(name,options = {})
        name = name.to_sym
        myscopes[name] = lambda { |proxy_scope| Scope.new(proxy_scope,options) }

        (class << self; self end).instance_eval do
          define_method name do
            myscopes[name].call(self) 
          end
        end
      end

      class Scope
        attr_reader :proxy_scope, :proxy_options
        delegate :with_scope,  :to => :proxy_scope                
        def initialize(proxy_scope, options)
          @proxy_scope, @proxy_options = proxy_scope, options
        end

        def inspect
          load_found
        end

        def load_found
          find(:all)
        end

        def method_missing(method, *args, &block)
          if proxy_scope.myscopes.include?(method)
            proxy_scope.myscopes[method].call(self)
          else
            with_scope :find => proxy_options do
              proxy_scope.send(method,*args)
            end
          end
        end

      end # end of class Scope

    end # end of module ClassMethods

  end # endof module MynamedScope
end
ActiveRecord::Base.send(:include, ActiveRecord::MynamedScope)

class User < ActiveRecord::Base
  mynamed_scope :active, :conditions => {:status =>  'active'}
  mynamed_scope :male, :conditions => {:gender => 'm'}
end

 原文章参考地址:http://www.neeraj.name/blog/articles/751-under-the-hood-how-named_scope-works

 

 

文章二、

It looks like Nick Kallen’s wildly popular has_finder plugin will be making its way into Rails 2.x in the form of named_scope . Observe:

All the goodness you’ve come to love in has_finder is now available as named_scope – plus you get some extra goodies too. User.all is given to you for free as an alias for User.find(:all) .

class User < ActiveRecord::Base
  named_scope :active, :conditions => {:active => true}
  named_scope :inactive, :conditions => {:active => false}
  named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end

# Standard usage
User.active    # same as User.find(:all, :conditions => {:active => true})
User.inactive # same as User.find(:all, :conditions => {:active => false})
User.recent   # same as User.find(:all, :conditions => ['created_at > ?', 1.week.ago])

# They're nest-able too!
User.active.recent
  # same as:
  # User.with_scope(:conditions => {:active => true}) do
  #   User.find(:all, :conditions => ['created_at > ?', 1.week.ago])
  # end
 

Advanced

For those with more discriminating needs, don’t forget some of these has_finder tidbits:

Passing Arguments

Pass in arguments to your named scopes to specify conditions (or other props) at run-time.

class User < ActiveRecord::Base
  named_scope :registered, lambda { |time_ago| { :conditions => ['created_at > ?', time_ago] }
end

User.registered 7.days.ago # same as User.find(:all, :conditions => ['created_at > ?', 7.days.ago])
 

Named Scope Extensions

Extend named scopes (in a similar fashion to association extensions ).

class User < ActiveRecord::Base
  named_scope :inactive, :conditions => {:active => false} do
    def activate
      each { |i| i.update_attribute(:active, true) }
    end
  end
end

# Re-activate all inactive users
User.inactive.activate
 

Anonymous Scopes

You can also pass around scopes as first class objects using scoped (a named scoped provided to you for free) as a way to build hairy queries on the fly.

# Store named scopes
active = User.scoped(:conditions => {:active => true})
recent = User.scoped(:conditions => ['created_at > ?', 7.days.ago])

# Which can be combined
recent_active = recent.active

# And operated upon
recent_active.each { |u| ... }
 

named_scope is a truly great feature. If you haven’t started using it yet, do so. You won’t know how you lived without it. Major thanks goes out to Nick.

分享到:
评论

相关推荐

    The+DevOps+2.2+Toolkit_Self-Healing+Clusters-Packt+Publishing(2018).epub

    It seems that with each new book the scope gets fuzzier and less precise. When I started writing Test-Driven Java Development the scope of the whole book was done in advance. I had a team working with...

    Programming iOS 11_Dive Deep into Views,Controllers, and Frameworks 2018.pdf

    The two-book architecture should, I believe, render the size and scope of each book tractable for readers. Together, they provide a complete grounding in the knowledge needed to begin writ‐ ing iOS ...

    Beginning Python (2005).pdf

    A Little Bit About the Internet Protocol 309 Internet Addresses 309 Internet Ports 310 Sending Internet E-mail 311 The E-mail File Format 311 MIME Messages 313 MIME Encodings: Quoted-printable ...

    Hands-On Database An IntroductIon to Database design and development 2nd

    and Sharon remembers something from a systems analysis class about UML diagrams called Use Case diagrams. She uses these diagrams to graphically show how each actor—tutor, student, and supervisor—...

    微软内部资料-SQL性能优化3

    Another type of table lock is a schema stability lock (Sch-S) and is compatible with all table locks except the schema modification lock (Sch-M). The schema modification lock (Sch-M) is incompatible ...

    Java邮件开发Fundamentals of the JavaMail API

    With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, ...

    ActiveState Komodo IDE 10.2.1.89853 Setup + Keygen

    that if something didn't make sense then it didn't deserve a default binding, the user can define these themselves. We also reviewed other editors complete default keybinding sets to find ...

    PostgreSQL 9.0 High Performance

    Filled with advice about what you should be doing; how to build experimental databases to explore performance topics, and then move what you've learned into a production database environment. Covers ...

    Universal-USB-Installer

    with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute ...

    beginning_portable_shell_scripting_from_novice_to_professional.pdf

    Replacing Patterns with Regular Expressions . . . . . . . . . . . . . . . . . . .39 Common Pitfalls of Regular Expressions . . . . . . . . . . . . . . . . . . . . . . .40 What’s Next? . . . . . . . ....

    外文翻译 stus MVC

    If you cannot find something you need in the library, contribute. In addition, Struts provides a starting point if you are learning JSP tag technology. • Open source You have all the advantages of...

    ICS delphixe10源码版

    - About SSL - Support - Release notes - Midware - Known problems - Special thanks Legal issues: ------------- Copyright (C) 1997-2016 by Fran鏾is PIETTE Rue de Grady 24, 4053 Embourg, Belgium ...

    AngularJS - Novice to Ninja.pdf.pdf )

    Doing Something Cool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Introducing Our Demo Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    ISO/IEC 27005:2011-EN

    NoTE 1 Risk analysis provides the basis for risk evaluation and decisions about risk treatment NoTE 2 Risk analysis includes risk estimation 3.11 risk assessment overall process of risk ...

    Python Power - The Comprehensive Guide (2008).pdf

    About Python ............................................................................................1 What Is Python? ................................................................................

Global site tag (gtag.js) - Google Analytics