1

We have a Rails application in which an after_create is dynamically added to an ActiveRecord model from an initializer.

We've tried instance_eval

Foo.instance_eval do
  send "after_create", lambda{|r| r.some_method}
end

and class_eval

Foo.class_eval do
  after_create lambda{|r| r.some_method}
end

When running Foo.new._create_callbacks just after creating them it returns both of the callbacks.

After doing a request to the Rails server the two callbacks disappear.

This problem only happens in development. Staging and Production are working fine.

When setting the config.cache_classes = true in the development.rb the callbacks will persist and not disappear.

We have replicated this code in other applications and it works fine, so maybe it is a configuration issue.

NOTE: We are using subdomains with lvh.me

  • Rails 3.1.1
  • Ruby 1.9.2-p180

Thanks :)

rogeliog
  • 3,632
  • 4
  • 27
  • 26
  • 1
    Makes sense: the callback chain is recreated on each request due to class reload in dev mode – apneadiving Aug 29 '12 at 20:46
  • But why is it that in other applications works just fine? – rogeliog Aug 29 '12 at 20:54
  • Yep, both in Rails 3.1.1 and 1.9.x – rogeliog Aug 29 '12 at 20:58
  • All with `cache_classes` set to `false`? – apneadiving Aug 29 '12 at 20:59
  • Yes, same `development.rb` :( – rogeliog Aug 29 '12 at 21:03
  • Since you're doing this dynamically, you're going to keep experiencing this issue in dev mode, since it reloads your env on each request (so that changes get applied). IDK why you're doing it dynamically, though, and I don't know why you're doing it to instances rather than the class. Frankly, it sounds like the kind of thing that should be declared on the class, or in a Railtie. – Joshua Cheek Aug 29 '12 at 21:46
  • It is done in an initializer because it will be a setup file for a Gem that will add a callback to an ActiveRecord model – rogeliog Aug 29 '12 at 21:50

2 Answers2

2

This question seems to be a similar problem, about monkey patching in development mode, and it has a potential solution:

How to monkey-patch code that gets auto-loaded in Rails?

Community
  • 1
  • 1
matthew.tuck
  • 1,267
  • 9
  • 11
0

In rails during development mode, all models are reloaded when a new request comes in. This is useful because you don't have to restar the server each time you change something. However, in prod this does not happen since there is a performance penalty. The issue here is initializers only get run during initialization of the rails app. Might I ask why you are trying to set after_create in the initializer and not the model itself?

moger777
  • 1,117
  • 11
  • 16