Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload the rails console

Regarding the use of Rails console, when I make some change on a model, do I need to reload the rails console every time to make that change reflects?

For example, I have my original code as follows:

class Article < ActiveRecord::Base   validates :title, :presence => true   validates :body, :presence => true end 

Later, I want to add some additional attribute as below.

class Article < ActiveRecord::Base   validates :title, :presence => true   validates :body, :presence => true    def long_title     "#{title} - #{published_at}"   end end 

Does it need to run the command "reload!" every time to be able to do the "long_title" method call? Otherwise, I will get an error saying as the attribute hasn't been defined. and Why do we need to perform that manually?

like image 690
Sarun Sermsuwan Avatar asked Oct 20 '11 03:10

Sarun Sermsuwan


People also ask

What does reload do in Rails?

Reloads the attributes of object(here @user) from the database. It always ensures object has latest data that is currently stored in database.

How do you clear a Ruby console?

Clearing the Console You can also use Ctrl + L to clear the screen, which works on both Mac and Linux. If you're on Windows, the only way we're aware of to clear the console is by typing system('cls') . The Windows cls command clears the screen, and the Ruby system method runs that command in a subshell.


2 Answers

Yes, you need to call reload! as this will clear the loaded constants that have been loaded and will load them as they're referenced in the console.

If you have old objects from before the reload! you will need to call reload on these individual objects or find new objects and work with them if you want to try out the new method.

As an alternative, I would really recommend looking into a testing framework such as RSpec which gives you repeatable tests and a safety net for your application.

It looks like you're trying to use the console as a testing tool for new functionality in your application, which is what RSpec is better suited for. The console is really good for experimentation.

like image 158
Ryan Bigg Avatar answered Oct 18 '22 19:10

Ryan Bigg


rails console does not reload classes after they have been referenced.

If it did it would have to make a call out to the file system to figure out which files had changed for every command.

rails server on the other hand will reload changed classes in between requests in development mode.

I'm guessing you are keeping the console open due to the rails console start up time. I'm not sure what your application is, and am unsure as to why the console is open during development. However, if you are trying to verify changes might I recommend testing with unit test or rspec and at that point you can use spork to speed up the start up time.

like image 33
daicoden Avatar answered Oct 18 '22 18:10

daicoden