Module: Switcher::ActiveRecord

Defined in:
lib/switcher/adapters/active_record.rb

Defined Under Namespace

Modules: ClassMethods, Initializer

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/switcher/adapters/active_record.rb', line 46

def self.included(base)
  base.extend Switcher::ClassMethods
  base.extend Switcher::ActiveRecord::ClassMethods

  base.class_eval do
    after_initialize do
      self.class.class_variable_get(:@@__specs__).each do |spec|
        spec_name     = spec.name
        state_current = read_attribute(spec_name)
        state_prev    = (has_attribute?("#{spec_name}_prev") ? read_attribute("#{spec_name}_prev") : nil)

        self.instance_variable_set(:"@#{spec_name}_statement", Statement.new(self, spec, state_current, state_prev))
      end
    end
  end
end

Instance Method Details

#switch(event, *args) ⇒ Object



63
64
65
# File 'lib/switcher/adapters/active_record.rb', line 63

def switch(event, *args)
  switch_from(self.class, event, *args)
end

#switch_from(orig, event, *args) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/switcher/adapters/active_record.rb', line 67

def switch_from(orig, event, *args)
  return false unless (self.respond_to?(:"can_#{event}?") and self.send(:"can_#{event}?"))

  self.class.class_variable_get(:@@__specs__).each do |spc|
    spc_name = spc.name

    self.instance_variable_get(:"@#{spc_name}_statement").publish(event, orig, args)

    write_attribute(spc_name, self.send(:"#{spc_name}"))
    if has_attribute?("#{spc_name}_prev")
      write_attribute("#{spc_name}_prev", self.send(:"#{spc_name}_prev"))
    end
  end

  true
end