How can I reload a script in IRB? - ruby

I am writing a Ruby script for use in the Rails environment, but I chose to run it from irb because reloading the Rails console can be a pain. Now the wait time is much shorter from irb, but I'm bothered that I have to restart irb and require the script everytime I make a change. Is there a simpler way of reloading a script from irb?
I found a method in this thread, but that only applies to gem files apparently. My require statement looks like this
require "#{File.expand_path(__FILE__)}/../lib/query"
EDIT: Having tried load rather than require, I still couldn't get it to work. I can't get a stop on these errors.
ruby-1.9.2-p0 > load "#{File.expand_path(__FILE__)}/../lib/query.rb"
LoadError: no such file to load -- /Users/newuser/Dropbox/Sites/rails/hacknyc/(irb)/../lib/query.rb

In irb, File.expand_path(__FILE__)} will just return "#{path you ran irb from}/(irb)". Which creates a path that doesn't actually exist. Luckily all file paths are relative to where you ran irb anyway. This means all you need is:
load "lib/query.rb"
If you want to use the __FILE__ in an actual file, that's fine, but don't expect it to produce a valid path in irb. Because an irb there is no "file" at all, so it cannot return valid path at all.
Also, __FILE__ will work fine if used in a file loaded into irb via load or require. Cause that's kinda what it's for.

Instead of using require, try load. The former only loads a source file once, while the latter loads it every time you call it.

according to this link you need to load your file and do not forget the extention.
Here is a fancier version to use too at this link number 2 which could be helpful for you too.
You may want to try hashing out why your rails console isn't working for you though.

I think load is what you are looking for.

Related

Update libraries after manual change

So I started working on my first open-source contribution in ruby. There I have the library I'm working on in the /lib/ folder. Now when I tried changing the code, my program (which uses the library) still uses the old code.
For example: Broke a function on purpose by deleting its end keyword (which should be causing an immediate crash), but it kept working perfectly after I did.
Another example was changing the code in such a way it should still work (mutating the output string) but it still returned the old string.
user~$ bin/ruby-hyphen -V "this is a test sentence"
this is a test sen-tence
Does anyone know if I have to tell the runtime to refresh it or something along those lines?
I found out why that happened. The file has a *.gemspec, which made it act as if it was a gem. To see the changes I needed to enter:
gem build *.gemspec
bundle exec rake install
Or, if you want to develop quicker: change everywhere you require it into a require_relative. That should also fix it. I hope this question helps someone in the future!

How to see the source code for an "update!' method

I have a web site that is killed due to a memory overflow. It is triggered during a PUT request coming from a users web browser. Unfortunately, the logs are not helpful in this case. I have traced the issue down to this method definition:
# app/controllers/registrations/profiles_controller.rb
def update
update! do |success, failure|
success.html { redirect_to edit_registration_diagnosis_path }
failure.html do
build_diagnosis
render 'edit'
end
end
end
I want to see the source code for this update! method. How do I ask ruby or rails or bash/grep to show me this source code?
I tried:
git grep 'def update!' # no results
My env:
$ rails --version
Rails 3.2.22.5
$ ruby --version
ruby 1.9.3p551
The libraries are not in the same directory as your Rails app, they'll be wherever your Ruby versions are, which differs depending on which version manager you used to install it.
The Rails docs are online at http://api.rubyonrails.org/, or you could use a gem like pry-byebug to step into the method during execution. As Ruby is object oriented and uses an inheritance chain to find an object that responds to a given message, this is the best way to really know which method is being called at any given point in the application's execution.
Add gem 'pry-byebug' to your gemfile, bundle install and then insert binding.pry at the top of your update method. Once execution pauses you can easily step into the method.
You can use byebug gem to see what is happening at each step in your method.
As others have said, the code in your app is not the full set of code that is running. So grep won't work here. You may also run into the issue where the same method is defined multiple times, and grep won't help there, either.
The best solution I've found is using pry. It looks like this is a Rails project, so you can get results most easily by adding the following to your Gemfile:
# Gemfile
gem "pry-rails"
gem "pry-doc"
At this point, the world is your oyster.
The easiest way to start learning how to use this is to add a binding.pry in your code execution where you want to explore. Then run the code in test or development environments, and your server will stop and give you a console at that line. Then you just show-source update! and you'll see where the method is defined.
So step 1, use pry and explore its many plugin libraries.
Step 2 is to try out solargraph in your text editor. It's not as powerful as pry, but it can help you jump to method definitions within your project easily. https://solargraph.org
Step 3 check out the premium text editor RubyMine, as it has support for this sort of thing and much more, though it's not free. https://www.jetbrains.com/help/ruby/getting-started.html

Ruby code auto-reloaded without Rails

Working with Rails, Sinatra, Padrino... I got used to my code being auto-reloaded when I made modifications.
How can I get the same behavior while working on plain Ruby gem projects which are not a Rack based web framework.
I would like to just launch a pry console and inmediatly being able to test the latest modifications of my source code.
You just need to define a method somewhere that clears the old stuff from memory, and re-load all of the files that comprise your gem:
def reload!
Object.send(:remove_const, :ProjectNamespace)
path = File.expand_path("../", __FILE__)
Dir.glob("#{path}/**/*.rb") { |f| load f }
end
Since you're using Pry, you can define this in your project's .pryrc if you'd like to keep it out of your the code base.
You can even define the reload logic within your inside your module, and for as long as its included among the files you're reloading, all will be well:
module ProjectNamespace
module_function
def reload!
# Reload code
end
end
ProjectNamespace.reload!
If you're in need of a more managed solution (e.g. timed reloads) you should look into a library like Rubyworks' autoreload.
I would create a run.rb script that forks a process and runs your code in that separate process. Using https://github.com/thibaudgg/rb-fsevent in the parent process to watch your file system for changes, kill the child process whenever a FS change is detected and fork a new child with your updated code.
After some exploration and trying the given answers, I realized that I was thinking about my problem the wrong way.
Although it is nice having a project reload, this requires certain preparation.
For Ruby I find far more convenient having a custom shortcut on my editor to:
save file
send a load file/path.rb command to my Pry session
That does not require any type of extra code or configuration for each project. However the other answers can be combined with Guard to have auto-reloads. That was actually the title of my question, but now I realized that one keystroke solution is more practical.

PhantomJS + CasperJS from Ruby - Reuse Code?

I am calling CasperJS from the backend of my Ruby on Rails application using Open3.popen3 to make a command line call. The filename (in my case CoffeeScript) is the first argument followed by options.
Many of my coffee files do similar tasks. I see examples of of how to reuse code with modules, but I think that's a NodeJS only thing.
Any suggestions how I might reuse common code in my situation? I'm really getting horribly un-DRY.
UPDATE:
hexid's answer is correct. What I was missing when I tried it before is that you need the rooted file path, not relative the current file path:
my_module = require('/rooted/path/to/the/file.coffee')
PhantomJS has support for CommonJS' require.
You won't, however, be able to require NodeJS modules because PhantomJS doesn't run on NodeJS, but instead on a version of Webkit that is included in QT.

Create convenience functions (batch commands) in Ruby console

During development I found myself checking the some results in the Ruby console everyday. This is done by typing the same commands with different parameters every time. However these command can be long, or sometimes several commands need to run sequentially.
For example:
Nokogiri.HTML(open(Rails.root.join('page/p1.html')))
I am wondering if it is possible to specify some convenience functions, which automatically gets loaded when I run the console? So I can call complex calls anytime I want in the console.
I also heard that there are console replacements. So it doesn't have to be the native console, as long as it offers similar functionalities.
Not sure about automatically, but you can create a ruby module, put all your useful stuff in there as methods, and just require/include that at the start of using the console.
As d11wtq pointed out, according to the console you use, you can use the its configuration file to write your own convenience functions:
IRB has ~/.irbrc
PRY has ~/.pryrc
RIB has ~/.rib/config.rb
Place the code in these and you can call them in the console.

Resources