Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I reload a model in rails console?

> rvm list
rvm rubies

=* ruby-1.9.2-p290 [ i686 ]
   ruby-1.9.3-p194 [ i686 ]

> rails -v
Rails 3.1.1

Related, but didn't answer: Is there a Rails Console command (Rails 3+) to reload changed code?

I'm using the Rails console to try and figure out why a method in my model isn't being called. The model is in ./app/models/product.rb. I'm changing a method from being called as self.trim_history to trim_history. I'm still wrapping my head around when to call a method as self.do_stuff or just do_stuff.

Well in the course of figuring this out I've run into a problem with reload!. My understanding was that reload! would load all the models and controllers again, but that doesn't seem to be working. When I debug my code, the line that I've changed to be do_stuff is still showing as self.do_stuff in the debugger.

I've attempted to solve this with reload!, no fix. I've reloaded the object from the database after reloading, no fix. I've loaded the model directly with load './app/models/product.rb', then loaded the object from the db, no fix. I've verified that the object is being changed with tail.

What's the best way to reload a model in the rails console? Do I have to re-start the console every time my model code changes? Is there some way to just dump all of the existing models and their code without reloading the console?

Edit: this got stranger. I now suspect that my code is being reloaded but the debugger is not reflecting the new code. When I step through the code, the old code is there, but the new code is being executed. I tested this by adding a raise -- the raise never shows in the debugger but it is raised. Wat?

Is there something I need to do with the debugger to get it to see the reloaded code? This looks like a bug...

like image 675
jcollum Avatar asked May 05 '12 19:05

jcollum


1 Answers

reload! doesn't reinitialize existing objects, it just reloads the code. If you create a new instance of the class it should reflect the changes.

like image 118
Chris Schmitz Avatar answered Oct 05 '22 12:10

Chris Schmitz