1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activerecord/test/models/bulb.rb
Jon Leighton 0a12a5f816 Deprecate eager-evaluated scopes.
Don't use this:

    scope :red, where(color: 'red')
    default_scope where(color: 'red')

Use this:

    scope :red, -> { where(color: 'red') }
    default_scope { where(color: 'red') }

The former has numerous issues. It is a common newbie gotcha to do
the following:

    scope :recent, where(published_at: Time.now - 2.weeks)

Or a more subtle variant:

    scope :recent, -> { where(published_at: Time.now - 2.weeks) }
    scope :recent_red, recent.where(color: 'red')

Eager scopes are also very complex to implement within Active
Record, and there are still bugs. For example, the following does
not do what you expect:

    scope :remove_conditions, except(:where)
    where(...).remove_conditions # => still has conditions
2012-03-21 22:18:18 +00:00

41 lines
1 KiB
Ruby

class Bulb < ActiveRecord::Base
default_scope { where(:name => 'defaulty') }
belongs_to :car
attr_protected :car_id, :frickinawesome
attr_reader :scope_after_initialize, :attributes_after_initialize
after_initialize :record_scope_after_initialize
def record_scope_after_initialize
@scope_after_initialize = self.class.scoped
end
after_initialize :record_attributes_after_initialize
def record_attributes_after_initialize
@attributes_after_initialize = attributes.dup
end
def color=(color)
self[:color] = color.upcase + "!"
end
def self.new(attributes = {}, options = {}, &block)
bulb_type = (attributes || {}).delete(:bulb_type)
if options && options[:as] == :admin && bulb_type.present?
bulb_class = "#{bulb_type.to_s.camelize}Bulb".constantize
bulb_class.new(attributes, options, &block)
else
super
end
end
end
class CustomBulb < Bulb
after_initialize :set_awesomeness
def set_awesomeness
self.frickinawesome = true if name == 'Dude'
end
end