1
0
Fork 0
mirror of https://github.com/aasm/aasm synced 2023-03-27 23:22:41 -04:00

avoiding memory leak in Rails 3 development mode (where cache_classes == false); drawback is, that now the state machine won't be re-declared on each request; thus, changes in the state machine will force you to restart the Rails server (but this still is better than the memory leak)

This commit is contained in:
Thorsten Böttger 2011-04-01 09:22:54 +02:00
parent 7fe7e2ed57
commit a6f77b5fa4
3 changed files with 61 additions and 7 deletions

View file

@ -1,13 +1,12 @@
class AASM::StateMachine
def self.[](*args)
(@machines ||= {})[args]
def self.[](clazz)
(@machines ||= {})[clazz.to_s]
end
def self.[]=(*args)
val = args.pop
(@machines ||= {})[args] = val
def self.[]=(clazz, machine)
(@machines ||= {})[clazz.to_s] = machine
end
attr_accessor :states, :events, :initial_state, :config
attr_reader :name

18
test/models/process.rb Normal file
View file

@ -0,0 +1,18 @@
module Models
class Process
include AASM
aasm_state :sleeping
aasm_state :running
aasm_state :suspended
aasm_event :start do
transitions :from => :sleeping, :to => :running
end
aasm_event :stop do
transitions :from => :running, :to => :suspended
end
end
end

View file

@ -0,0 +1,37 @@
require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class StateMachineTest < Test::Unit::TestCase
context "state machines" do
should "be created without memory leak" do
assert_equal 1, AASM::StateMachine.instance_variable_get("@machines").size # AuthMachine
assert_number_of_objects AASM::SupportingClasses::State, 5 # AuthMachine
assert_number_of_objects AASM::SupportingClasses::Event, 10 # AuthMachine
assert_number_of_objects AASM::SupportingClasses::StateTransition, 18 # AuthMachine
load File.expand_path(File.dirname(__FILE__) + '/../models/process.rb')
assert_equal 2, AASM::StateMachine.instance_variable_get("@machines").size # AuthMachine + Process
assert_number_of_objects Models::Process, 0
assert_number_of_objects AASM::SupportingClasses::State, 8 # AuthMachine + Process
assert_number_of_objects AASM::SupportingClasses::Event, 12 # AuthMachine + Process
assert_number_of_objects AASM::SupportingClasses::StateTransition, 20 # AuthMachine + Process
Models.send(:remove_const, "Process") if Models.const_defined?("Process")
load File.expand_path(File.dirname(__FILE__) + '/../models/process.rb')
assert_equal 2, AASM::StateMachine.instance_variable_get("@machines").size # AuthMachine + Process
assert_number_of_objects AASM::SupportingClasses::State, 8 # AuthMachine + Process
assert_number_of_objects AASM::SupportingClasses::Event, 12 # AuthMachine + Process
assert_number_of_objects AASM::SupportingClasses::StateTransition, 20 # AuthMachine + Process
end
end
private
def assert_number_of_objects(clazz, num)
count = ObjectSpace.each_object(clazz) {}
assert_equal num, count, "#{num} expected, but we had #{count} #{clazz}"
end
end