metaskills-grouped_scope 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/test/helper.rb ADDED
@@ -0,0 +1,108 @@
1
+ require File.join(File.dirname(__FILE__),'lib/boot') unless defined?(ActiveRecord)
2
+ require 'test/unit'
3
+ require 'shoulda'
4
+ require 'mocha'
5
+ require 'factory_girl'
6
+ require 'lib/test_case'
7
+ require 'grouped_scope'
8
+
9
+ class GroupedScope::TestCase
10
+
11
+ def setup_environment(options={})
12
+ options.reverse_merge! :group_column => :group_id
13
+ setup_database(options)
14
+ Department.create! :name => 'IT'
15
+ Department.create! :name => 'Human Resources'
16
+ Department.create! :name => 'Finance'
17
+ end
18
+
19
+ protected
20
+
21
+ def setup_database(options)
22
+ ActiveRecord::Base.class_eval do
23
+ silence do
24
+ connection.create_table :employees, :force => true do |t|
25
+ t.column :name, :string
26
+ t.column :email, :string
27
+ t.column options[:group_column], :integer
28
+ end
29
+ connection.create_table :reports, :force => true do |t|
30
+ t.column :title, :string
31
+ t.column :body, :string
32
+ t.column :employee_id, :integer
33
+ end
34
+ connection.create_table :departments, :force => true do |t|
35
+ t.column :name, :string
36
+ end
37
+ connection.create_table :department_memberships, :force => true do |t|
38
+ t.column :employee_id, :integer
39
+ t.column :department_id, :integer
40
+ t.column :meta_info, :string
41
+ end
42
+ connection.create_table :legacy_employees, :force => true, :id => false do |t|
43
+ t.column :name, :string
44
+ t.column :email, :string
45
+ t.column options[:group_column], :integer
46
+ end
47
+ connection.create_table :legacy_reports, :force => true do |t|
48
+ t.column :title, :string
49
+ t.column :body, :string
50
+ t.column :email, :string
51
+ end
52
+ connection.create_table :foo_bars, :force => true do |t|
53
+ t.column :foo, :string
54
+ t.column :bar, :string
55
+ end
56
+ end
57
+ end
58
+ end
59
+
60
+ end
61
+
62
+ class Employee < ActiveRecord::Base
63
+ has_many :reports do ; def urgent ; find(:all,:conditions => {:title => 'URGENT'}) ; end ; end
64
+ has_many :taxonomies, :as => :classable
65
+ has_many :department_memberships
66
+ has_many :departments, :through => :department_memberships
67
+ grouped_scope :reports, :departments
68
+ end
69
+
70
+ class Report < ActiveRecord::Base
71
+ named_scope :with_urgent_title, :conditions => {:title => 'URGENT'}
72
+ named_scope :with_urgent_body, :conditions => "body LIKE '%URGENT%'"
73
+ belongs_to :employee
74
+ def urgent_title? ; self[:title] == 'URGENT' ; end
75
+ def urgent_body? ; self[:body] =~ /URGENT/ ; end
76
+ end
77
+
78
+ class Department < ActiveRecord::Base
79
+ named_scope :it, :conditions => {:name => 'IT'}
80
+ named_scope :hr, :conditions => {:name => 'Human Resources'}
81
+ named_scope :finance, :conditions => {:name => 'Finance'}
82
+ has_many :department_memberships
83
+ has_many :employees, :through => :department_memberships
84
+ end
85
+
86
+ class DepartmentMembership < ActiveRecord::Base
87
+ belongs_to :employee
88
+ belongs_to :department
89
+ end
90
+
91
+ class LegacyEmployee < ActiveRecord::Base
92
+ set_primary_key :email
93
+ has_many :reports, :class_name => 'LegacyReport', :foreign_key => 'email'
94
+ grouped_scope :reports
95
+ alias_method :email=, :id=
96
+ end
97
+
98
+ class LegacyReport < ActiveRecord::Base
99
+ belongs_to :employee, :class_name => 'LegacyEmployee', :foreign_key => 'email'
100
+ end
101
+
102
+ class FooBar < ActiveRecord::Base
103
+ has_many :reports
104
+ grouped_scope :reports
105
+ end
106
+
107
+
108
+
data/test/lib/boot.rb ADDED
@@ -0,0 +1,32 @@
1
+ require 'rubygems'
2
+
3
+ plugin_root = File.expand_path(File.join(File.dirname(__FILE__),'..'))
4
+ framework_root = ["#{plugin_root}/rails", "#{plugin_root}/../../rails"].detect { |p| File.directory? p }
5
+ rails_version = ENV['RAILS_VERSION']
6
+ rails_version = nil if rails_version && rails_version == ''
7
+
8
+ ['.','lib','test'].each do |plugin_lib|
9
+ load_path = File.expand_path("#{plugin_root}/#{plugin_lib}")
10
+ $LOAD_PATH.unshift(load_path) unless $LOAD_PATH.include?(load_path)
11
+ end
12
+
13
+ if rails_version.nil? && framework_root
14
+ puts "Found framework root: #{framework_root}"
15
+ $:.unshift "#{framework_root}/activesupport/lib", "#{framework_root}/activerecord/lib"
16
+ else
17
+ puts "Using rails#{" #{rails_version}" if rails_version} from gems"
18
+ if rails_version
19
+ gem 'rails', rails_version
20
+ else
21
+ gem 'activerecord'
22
+ end
23
+ end
24
+
25
+ require 'active_record'
26
+ require 'active_support'
27
+
28
+ gem 'mislav-will_paginate', '2.3.4'
29
+ require 'will_paginate'
30
+ WillPaginate.enable_activerecord
31
+ require 'named_scope'
32
+
@@ -0,0 +1,20 @@
1
+
2
+ unless Hash.instance_methods.include? 'except'
3
+
4
+ Hash.class_eval do
5
+
6
+ # Returns a new hash without the given keys.
7
+ def except(*keys)
8
+ rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
9
+ reject { |key,| rejected.include?(key) }
10
+ end
11
+
12
+ # Replaces the hash without only the given keys.
13
+ def except!(*keys)
14
+ replace(except(*keys))
15
+ end
16
+
17
+ end
18
+
19
+ end
20
+
@@ -0,0 +1,82 @@
1
+
2
+ unless Hash.instance_methods.include? 'except'
3
+ Hash.class_eval do
4
+
5
+ # Returns a new hash without the given keys.
6
+ def except(*keys)
7
+ rejected = Set.new(respond_to?(:convert_key) ? keys.map { |key| convert_key(key) } : keys)
8
+ reject { |key,| rejected.include?(key) }
9
+ end
10
+
11
+ # Replaces the hash without only the given keys.
12
+ def except!(*keys)
13
+ replace(except(*keys))
14
+ end
15
+
16
+ end
17
+ end
18
+
19
+ class ActiveRecord::Base
20
+ class << self
21
+
22
+ def first(*args)
23
+ find(:first, *args)
24
+ end
25
+
26
+ def last(*args)
27
+ find(:last, *args)
28
+ end
29
+
30
+ def all(*args)
31
+ find(:all, *args)
32
+ end
33
+
34
+ private
35
+
36
+ def find_last(options)
37
+ order = options[:order]
38
+ if order
39
+ order = reverse_sql_order(order)
40
+ elsif !scoped?(:find, :order)
41
+ order = "#{table_name}.#{primary_key} DESC"
42
+ end
43
+ if scoped?(:find, :order)
44
+ scoped_order = reverse_sql_order(scope(:find, :order))
45
+ scoped_methods.select { |s| s[:find].update(:order => scoped_order) }
46
+ end
47
+ find_initial(options.merge({ :order => order }))
48
+ end
49
+
50
+ def reverse_sql_order(order_query)
51
+ reversed_query = order_query.split(/,/).each { |s|
52
+ if s.match(/\s(asc|ASC)$/)
53
+ s.gsub!(/\s(asc|ASC)$/, ' DESC')
54
+ elsif s.match(/\s(desc|DESC)$/)
55
+ s.gsub!(/\s(desc|DESC)$/, ' ASC')
56
+ elsif !s.match(/\s(asc|ASC|desc|DESC)$/)
57
+ s.concat(' DESC')
58
+ end
59
+ }.join(',')
60
+ end
61
+
62
+ end
63
+ end
64
+
65
+ ActiveRecord::Associations::AssociationCollection.class_eval do
66
+
67
+ def last(*args)
68
+ if fetch_first_or_last_using_find? args
69
+ find(:last, *args)
70
+ else
71
+ load_target unless loaded?
72
+ @target.last(*args)
73
+ end
74
+ end
75
+
76
+ private
77
+
78
+ def fetch_first_or_last_using_find?(args)
79
+ args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] || !@target.blank? || args.first.kind_of?(Integer))
80
+ end
81
+
82
+ end
@@ -0,0 +1,168 @@
1
+ module ActiveRecord
2
+ module NamedScope
3
+ # All subclasses of ActiveRecord::Base have two named_scopes:
4
+ # * <tt>all</tt>, which is similar to a <tt>find(:all)</tt> query, and
5
+ # * <tt>scoped</tt>, which allows for the creation of anonymous scopes, on the fly: <tt>Shirt.scoped(:conditions => {:color => 'red'}).scoped(:include => :washing_instructions)</tt>
6
+ #
7
+ # These anonymous scopes tend to be useful when procedurally generating complex queries, where passing
8
+ # intermediate values (scopes) around as first-class objects is convenient.
9
+ def self.included(base)
10
+ base.class_eval do
11
+ extend ClassMethods
12
+ named_scope :scoped, lambda { |scope| scope }
13
+ end
14
+ end
15
+
16
+ module ClassMethods
17
+ def scopes
18
+ read_inheritable_attribute(:scopes) || write_inheritable_attribute(:scopes, {})
19
+ end
20
+
21
+ # Adds a class method for retrieving and querying objects. A scope represents a narrowing of a database query,
22
+ # such as <tt>:conditions => {:color => :red}, :select => 'shirts.*', :include => :washing_instructions</tt>.
23
+ #
24
+ # class Shirt < ActiveRecord::Base
25
+ # named_scope :red, :conditions => {:color => 'red'}
26
+ # named_scope :dry_clean_only, :joins => :washing_instructions, :conditions => ['washing_instructions.dry_clean_only = ?', true]
27
+ # end
28
+ #
29
+ # The above calls to <tt>named_scope</tt> define class methods <tt>Shirt.red</tt> and <tt>Shirt.dry_clean_only</tt>. <tt>Shirt.red</tt>,
30
+ # in effect, represents the query <tt>Shirt.find(:all, :conditions => {:color => 'red'})</tt>.
31
+ #
32
+ # Unlike Shirt.find(...), however, the object returned by <tt>Shirt.red</tt> is not an Array; it resembles the association object
33
+ # constructed by a <tt>has_many</tt> declaration. For instance, you can invoke <tt>Shirt.red.find(:first)</tt>, <tt>Shirt.red.count</tt>,
34
+ # <tt>Shirt.red.find(:all, :conditions => {:size => 'small'})</tt>. Also, just
35
+ # as with the association objects, name scopes acts like an Array, implementing Enumerable; <tt>Shirt.red.each(&block)</tt>,
36
+ # <tt>Shirt.red.first</tt>, and <tt>Shirt.red.inject(memo, &block)</tt> all behave as if Shirt.red really were an Array.
37
+ #
38
+ # These named scopes are composable. For instance, <tt>Shirt.red.dry_clean_only</tt> will produce all shirts that are both red and dry clean only.
39
+ # Nested finds and calculations also work with these compositions: <tt>Shirt.red.dry_clean_only.count</tt> returns the number of garments
40
+ # for which these criteria obtain. Similarly with <tt>Shirt.red.dry_clean_only.average(:thread_count)</tt>.
41
+ #
42
+ # All scopes are available as class methods on the ActiveRecord::Base descendent upon which the scopes were defined. But they are also available to
43
+ # <tt>has_many</tt> associations. If,
44
+ #
45
+ # class Person < ActiveRecord::Base
46
+ # has_many :shirts
47
+ # end
48
+ #
49
+ # then <tt>elton.shirts.red.dry_clean_only</tt> will return all of Elton's red, dry clean
50
+ # only shirts.
51
+ #
52
+ # Named scopes can also be procedural.
53
+ #
54
+ # class Shirt < ActiveRecord::Base
55
+ # named_scope :colored, lambda { |color|
56
+ # { :conditions => { :color => color } }
57
+ # }
58
+ # end
59
+ #
60
+ # In this example, <tt>Shirt.colored('puce')</tt> finds all puce shirts.
61
+ #
62
+ # Named scopes can also have extensions, just as with <tt>has_many</tt> declarations:
63
+ #
64
+ # class Shirt < ActiveRecord::Base
65
+ # named_scope :red, :conditions => {:color => 'red'} do
66
+ # def dom_id
67
+ # 'red_shirts'
68
+ # end
69
+ # end
70
+ # end
71
+ #
72
+ #
73
+ # For testing complex named scopes, you can examine the scoping options using the
74
+ # <tt>proxy_options</tt> method on the proxy itself.
75
+ #
76
+ # class Shirt < ActiveRecord::Base
77
+ # named_scope :colored, lambda { |color|
78
+ # { :conditions => { :color => color } }
79
+ # }
80
+ # end
81
+ #
82
+ # expected_options = { :conditions => { :colored => 'red' } }
83
+ # assert_equal expected_options, Shirt.colored('red').proxy_options
84
+ def named_scope(name, options = {}, &block)
85
+ name = name.to_sym
86
+ scopes[name] = lambda do |parent_scope, *args|
87
+ Scope.new(parent_scope, case options
88
+ when Hash
89
+ options
90
+ when Proc
91
+ options.call(*args)
92
+ end, &block)
93
+ end
94
+ (class << self; self end).instance_eval do
95
+ define_method name do |*args|
96
+ scopes[name].call(self, *args)
97
+ end
98
+ end
99
+ end
100
+ end
101
+
102
+ class Scope
103
+ attr_reader :proxy_scope, :proxy_options
104
+
105
+ [].methods.each do |m|
106
+ unless m =~ /(^__|^nil\?|^send|^object_id$|class|extend|^find$|count|sum|average|maximum|minimum|paginate|first|last|empty\?|respond_to\?)/
107
+ delegate m, :to => :proxy_found
108
+ end
109
+ end
110
+
111
+ delegate :scopes, :with_scope, :to => :proxy_scope
112
+
113
+ def initialize(proxy_scope, options, &block)
114
+ [options[:extend]].flatten.each { |extension| extend extension } if options[:extend]
115
+ extend Module.new(&block) if block_given?
116
+ @proxy_scope, @proxy_options = proxy_scope, options.except(:extend)
117
+ end
118
+
119
+ def reload
120
+ load_found; self
121
+ end
122
+
123
+ def first(*args)
124
+ if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
125
+ proxy_found.first(*args)
126
+ else
127
+ find(:first, *args)
128
+ end
129
+ end
130
+
131
+ def last(*args)
132
+ if args.first.kind_of?(Integer) || (@found && !args.first.kind_of?(Hash))
133
+ proxy_found.last(*args)
134
+ else
135
+ find(:last, *args)
136
+ end
137
+ end
138
+
139
+ def empty?
140
+ @found ? @found.empty? : count.zero?
141
+ end
142
+
143
+ def respond_to?(method, include_private = false)
144
+ super || @proxy_scope.respond_to?(method, include_private)
145
+ end
146
+
147
+ protected
148
+ def proxy_found
149
+ @found || load_found
150
+ end
151
+
152
+ private
153
+ def method_missing(method, *args, &block)
154
+ if scopes.include?(method)
155
+ scopes[method].call(self, *args)
156
+ else
157
+ with_scope :find => proxy_options do
158
+ proxy_scope.send(method, *args, &block)
159
+ end
160
+ end
161
+ end
162
+
163
+ def load_found
164
+ @found = find(:all)
165
+ end
166
+ end
167
+ end
168
+ end
@@ -0,0 +1,85 @@
1
+
2
+ ActiveRecord::Associations::AssociationProxy.class_eval do
3
+ protected
4
+ def with_scope(*args, &block)
5
+ @reflection.klass.send :with_scope, *args, &block
6
+ end
7
+ end
8
+
9
+ class ActiveRecord::Base
10
+ class << self
11
+ def find(*args)
12
+ options = extract_options_from_args!(args)
13
+ validate_find_options(options)
14
+ set_readonly_option!(options)
15
+ case args.first
16
+ when :first then find_initial(options)
17
+ when :last then find_last(options)
18
+ when :all then find_every(options)
19
+ else find_from_ids(args, options)
20
+ end
21
+ end
22
+ private
23
+ def attribute_condition_with_named_scope(argument)
24
+ case argument
25
+ when ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope then "IN (?)"
26
+ else attribute_condition_without_named_scope(argument)
27
+ end
28
+ end
29
+ alias_method_chain :attribute_condition, :named_scope
30
+ end
31
+ end
32
+
33
+ ActiveRecord::Associations::HasManyAssociation.class_eval do
34
+ protected
35
+ def method_missing(method, *args, &block)
36
+ if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
37
+ super
38
+ elsif @reflection.klass.scopes.include?(method)
39
+ @reflection.klass.scopes[method].call(self, *args)
40
+ else
41
+ create_scoping = {}
42
+ set_belongs_to_association_for(create_scoping)
43
+
44
+ @reflection.klass.with_scope(
45
+ :create => create_scoping,
46
+ :find => {
47
+ :conditions => @finder_sql,
48
+ :joins => @join_sql,
49
+ :readonly => false
50
+ }
51
+ ) do
52
+ @reflection.klass.send(method, *args, &block)
53
+ end
54
+ end
55
+ end
56
+ end
57
+
58
+ ActiveRecord::Associations::HasManyThroughAssociation.class_eval do
59
+ protected
60
+ def method_missing(method, *args, &block)
61
+ if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
62
+ super
63
+ elsif @reflection.klass.scopes.include?(method)
64
+ @reflection.klass.scopes[method].call(self, *args)
65
+ else
66
+ @reflection.klass.with_scope(construct_scope) { @reflection.klass.send(method, *args, &block) }
67
+ end
68
+ end
69
+ end
70
+
71
+ ActiveRecord::Associations::HasAndBelongsToManyAssociation.class_eval do
72
+ protected
73
+ def method_missing(method, *args, &block)
74
+ if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
75
+ super
76
+ elsif @reflection.klass.scopes.include?(method)
77
+ @reflection.klass.scopes[method].call(self, *args)
78
+ else
79
+ @reflection.klass.with_scope(:find => { :conditions => @finder_sql, :joins => @join_sql, :readonly => false }) do
80
+ @reflection.klass.send(method, *args, &block)
81
+ end
82
+ end
83
+ end
84
+ end
85
+