pluginaweek / state_machine

Adds support for creating state machines for attributes on any Ruby class
http://www.pluginaweek.org
MIT License
3.74k stars 507 forks source link

Memory leak in #state_machine macro with anonymous classes #269

Closed jhuckabee closed 11 years ago

jhuckabee commented 11 years ago

I'm running into a memory leak issue with dynamic state machine definitions using anonymous classes. This is very similar to the example in the readme. I've created a trivial example that demonstrates the issue.

I've spent a few hours trying to narrow it down, but memory profiling in ruby has been quite the PITA. Before I spend any more time on it I wanted to see if anyone could point me in the right direction.

jhuckabee commented 11 years ago

I've boiled the problem down to the way helpers get dynamically defined on Machine objects in #define_helper. This gist summarizes the issue.

jhuckabee commented 11 years ago

This memory leak is unavoidable without a significant overhaul of how dynamic methods get created on the state machine class. This is because define_method is used to generated methods dynamically on the state machine class. See the caution at the end of this article.

At a minimum, a comment should probably be added to the README section on dynamic state machine definitions that points out that the example has a memory leak. There's no way to get rid of the instantiated Vehicle object. This gist illustrates the memory leak.

If you need dynamic state machine functionality, look at something like the soveran/micromachine gem. Its way less feature-complete, but worked for what I was doing.