Module: ConstantTableSaver::ActiveRecord3ClassMethods

Defined in:
lib/constant_table_saver.rb

Instance Method Summary collapse

Instance Method Details

#scoped(options = nil) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/constant_table_saver.rb', line 109

def scoped(options = nil)
  return super if options
  return super if respond_to?(:current_scoped_methods, true) && current_scoped_methods
  return super if respond_to?(:current_scope, true) && current_scope
  @cached_blank_scope ||= super.tap do |s|
    class << s
      def to_a
        return @records if loaded?
        super.each(&:freeze)
      end
      
      def find(*args)
        # annoyingly, the call to find to load a belongs_to passes :conditions => nil, which causes
        # the base find method to apply_finder_options and construct an entire new scope, which is
        # unnecessary and also means that it bypasses our find_one implementation (we don't interfere
        # with scopes or finds that actually do apply conditions etc.), so we check as a special case
        return find_with_ids(args.first) if args.length == 2 && args.last == {:conditions => nil}
        super
      end
  
      def find_first
        # the normal scope implementation would cache this anyway, but we force a load of all records,
        # since otherwise if the app used .first before using .all there'd be unnecessary queries
        to_a.first
      end
    
      def find_last
        # as for find_first
        to_a.last
      end
    
      def find_one(id)
        # see below re to_param
        cached_records_by_id[id.to_param] || raise(::ActiveRecord::RecordNotFound, "Couldn't find #{name} with ID=#{id}")
      end
      
      def find_some(ids)
        # see below re to_param
        ids.collect {|id| cached_records_by_id[id.to_param]}.tap do |results| # obviously since find_one caches efficiently, this isn't inefficient as it would be for real finds
          results.compact!
          raise(::ActiveRecord::RecordNotFound, "Couldn't find all #{name.pluralize} with IDs #{ids.join ','} (found #{results.size} results, but was looking for #{ids.size}") unless results.size == ids.size
        end
      end

      # in Rails 3.1 the associations code was rewritten to generalise its sql generation to support
      # more complex relationships (eg. nested :through associations).  however unfortunately, during
      # this work the implementation of belongs_to associations was changed so that it no longer calls
      # one of the basic find_ methods above; instead a vanilla target scope is constructed, a where()
      # scope to add the constraint that the primary key = the FK value is constructed, the two are
      # merged, and then #first is called on that scope.  frustratingly, all this complexity means that
      # our find_ hooks above are no longer called when dereferencing a belongs_to association; they
      # work fine and are used elsewhere, but we have to explicitly handle belongs_to target scope
      # merging to avoid those querying, which is a huge PITA.  because we want to ensure that we don't
      # end up accidentally caching other scope requests, we explicitly build a list of the possible
      # ARel constrained scopes - indexing them by their expression in SQL so that we don't need to
      # code in the list of all the possible ARel terms.  we then go one step further and make this
      # cached scope pre-loaded using the record we already have - there's sadly no external way to do
      # this so we have to shove in the instance variables.
      #
      # it will be clear that this was a very problematic ActiveRecord refactoring.
      def belongs_to_record_scopes
        @belongs_to_record_scopes ||= to_a.each_with_object({}) do |record, results|
          scope_that_belongs_to_will_want = where(table[primary_key].eq(record.id))
          scope_that_belongs_to_will_want.instance_variable_set("@loaded", true)
          scope_that_belongs_to_will_want.instance_variable_set("@records", [record])
          results[scope_that_belongs_to_will_want.to_sql] = scope_that_belongs_to_will_want
        end.freeze
      end

      def merge(other)
        if belongs_to_record_scope = belongs_to_record_scopes[other.to_sql]
          return belongs_to_record_scope
        end

        super other
      end
    
    private
      def cached_records_by_id
        # we'd like to use the same as ActiveRecord's finder_methods.rb, which uses:
        #  id = id.id if ActiveRecord::Base === id
        # but referencing ActiveRecord::Base here segfaults my ruby 1.8.7
        # (2009-06-12 patchlevel 174) [universal-darwin10.0]!  instead we use to_param.
        @cached_records_by_id ||= all.index_by {|record| record.id.to_param}
      end
    end
  end
end