aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/models/bulb.rb
blob: c1e491e5c5f114fbac9c05288f117a3f925f3389 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Bulb < ActiveRecord::Base
  default_scope { where(:name => 'defaulty') }
  belongs_to :car, :touch => true
  scope :awesome, -> { where(frickinawesome: true) }

  attr_reader :scope_after_initialize, :attributes_after_initialize

  after_initialize :record_scope_after_initialize
  def record_scope_after_initialize
    @scope_after_initialize = self.class.all
  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 = {}, &block)
    bulb_type = (attributes || {}).delete(:bulb_type)

    if bulb_type.present?
      bulb_class = "#{bulb_type.to_s.camelize}Bulb".constantize
      bulb_class.new(attributes, &block)
    else
      super
    end
  end
end

class CustomBulb < Bulb
  after_initialize :set_awesomeness

  def set_awesomeness
    self.frickinawesome = true if name == 'Dude'
  end
end

class FunkyBulb < Bulb
  before_destroy do
    raise "before_destroy was called"
  end
end

class FailedBulb < Bulb
  before_destroy do
    throw(:abort)
  end
end