Can you 'require' ruby file in irb session, automatically, on every command? - ruby

I am currently editing a file, and I'm using irb to test the api:
> require './file.rb'
> o = Object.new
> o.method
I then want to be able to edit the file.rb, and be able to see changes immediately. Example: assume new_method did not exist when I first required file.rb:
> o.new_method
Which will return an error. Is there a sandbox/developer mode or a method whereby I can achieve the above without having to reload the file every time? Require will not work after the first require, regardless. I assume worst case I'd have to use load instead.

I usually create a simple function like this:
def reload
load 'myscript.rb'
# Load any other necessary files here ...
end
With that, a simple reload will re-import all of the scripts that I'm working on. It's not automatic, but it's the closest thing that I've been able to come up with.
You may be able to override method_missing to call this function automatically when your object is invoked with a method that doesn't exist. I've never tried it myself, though, so I can't give any specific advice. It also wouldn't help if you're calling a method that already exists but has simply been modified.
In my own laziness, I've gone as far as mapping one of the programmable buttons on my mouse to the key sequence "reload<enter>". When I'm using irb, all it takes is the twitch of a pinky finger to reload everything. Consequently when I'm not using irb, I end up with the string "reload" inserted in documents unintentionally (but that's a different problem entirely).

This won't run every command, but you can include a file on every IRb session. ~/.irbrc is loaded each time you start an IRb session.
~/.irbrc
require "~/somefile.rb"
~/somefile.rb
puts "somefile loaded"
terminal
> irb
somefile loaded
irb(main):001:0>
~/.irbrc is loaded each time you start an irb session

What about require_dependency from ActiveSupport library?
require 'active_support/dependencies' #load it at the beginning
require_dependency 'myscript.rb'
Then require_dependency should track the changes in myscript file and reload it.

Related

Can't Load my Ruby File

OK SO I Am just picking Ruby up pretty much for the kicks and giggles... and Believe me when I say I'm stumped.
I want to create a bot for my Twitch stream and do it in Ruby because I found a fairly easy tut to follow along with, along with my reasoning skills. However I'm having a very hard time getting my command prompt or pry to load the file.
Here is my file JUST IN CASE
require 'socket'
TWITCH_HOST = "irc.twitch.tv"
TWITCH_PORT = 6667
class Fox
def initialize
#nickname = "mybotsname"
#password = "I have the proper oauth here"
#channel = "mytwitchchannel"
#socket = TCPSocket.open(TWITCH_HOST, TWITCH_PORT)
write_to_system "PASS #{#password}"
write_to_system "NICK #{#nickname}"
write_to_system "USER #{#nickname} 0 * #{#nickname}"
write_to_system "JOIN ##{#Channel}"
end
def write_to_system(message)
#socket.puts message
end
def write_to_chat(message)
write_to_system "PRIVMSG ##{#channel} :{message}"
end
end
Now, From what I gathered, I should beable to go into my command prompt and type pry
I get this.
Pry
Now, I want to run my program which is located in a dropbox (Private use)
I'm Still very new to the concept of Repl's as I've been working with Java mostly along with very LITTLE Experience in other languages. What am I doing wrong here? Why can I not get my file to load properly? I've also tried filepathing and got this.FilePathing
I'm sorry if this is a stupid question. It's just driving me absolutely bat-brain crazy. The reason this is driving me bonkers is the video I was watching, he didn't do anything different other than my guess is he was using Terminal instead of Command Prompt. I Wanted originally to do this through Cygwin but upon install of Pry I lost a bunch of Cygwin files and can no longer load Cygwin, I will re-install the over all program later and see what I can from there.
Sorry for no embedded pics.
Also, any easier way to do this I'm all ears. I've tried Komodo Edit 10 but it's not playing nice ether.
Require from LOAD_PATH
A Ruby module or class file needs to be in the LOAD_PATH to require it with Kernel#require. For example, if your file is named just_in_case.rb, you can use:
$LOAD_PATH.unshift '/path/to/dropbox/directory'
# Leave off the path and .rb extension.
require 'just_in_case'
Load from an absolute path
If you need to provide an absolute path, then you should use Kernel#load instead. For example:
# Use the absolute path and the .rb extension.
load '/path/to/dropbox/just_in_case.rb'
Caveats
There are some other differences in behavior between require, require_relative, and load, but they probably don't really matter within the limited scope of the question you asked except that there have historically been issues with Kernel#require_relative within the REPL. It may or may not work as expected now, but I would still recommend require or load for your specific use case.

Zip command in ruby block does not work without binding.pry

I have a block of code that executes a zip command from another class:
def zip_up_contents path name
Zipper.new path name
end
The problem is that it zips blank copies of all the files passed to it. But when I put a binding before the zip command like so:
def zip_up_contents path name
binding.pry
Zipper.new path name
binding.pry
end
it zips the files successfully. I know this by checking the resulting file's byte size from within pry on the second binding point with and without the first binding present. Without the binding, the zip archive's byte size is half what it should be, and with the binding it's the size I would expect.
The "Zipper" class simply calls the system zip with backticks. I don't think that's the problem because I've used that class without trouble in other contexts. The zip utility is Zip 3.0 on Ubuntu 10.04.
I have no idea why the presence of the binding makes a difference. If anyone has encountered anything similar, or has thoughts about how to better debug the issue, I'd appreciate hearing about it.
EDIT: For anyone encountering anything similar, I resolved this by calling fsync on the files prior to zipping them: http://www.ruby-doc.org/core-2.0.0/IO.html#method-i-fsync
I had this problem with some Rspec tests last week -- turned out to be a race condition. Is there any chance that the file hasn't been saved when you pass it to be zipped? I mean, maybe the binding.pry is just giving it a chance to catch up.

Should I use load or require in IRB?

I had the impression that I should use require 'some_path' to get a file or a library I want to use, but I couldn't get it to work, and load 'some_path' worked.
When are the different times when I should use these?
Also, is it possible to import a directory with the load or require commmands? I am trying to use a whole directory, but so far I could only get one file at a time with load.
You can use Dir to list all the files ending with .rb and require/load them
Dir["/path/to/dir/*.rb"].each { |file| load_your_file_here(file) }
I recommend requiring file and then including the module that file loads... If you are not using module or class inside your file than maybe you should reconsider your structure.
load might have some unintended consequences and it's not performant.
Once you call require for a file further calls of require will no longer require it again(i.e. will have no effect), while load will reload it every time you call it. As far as I know there is no way to load a whole directory.

I can't figure out the require in ruby

I'm new to Ruby
MakModule.rb
module Display
class Multiply
def Multiply.mul(first, second)
return first * second
end
end
end
MakRequire1.rb
require "Display"
puts Multiply.mul 5,6
MakRequire2.rb
require "MakModule.rb"
puts Multiply.mul 5,6
both file give me the error below
ruby: No such file or directory -- makRequire (LoadError)
How should I correct my code?
It is simply impossible that the code you posted here generates that error message. The error message says that you tried to require a file named makRequire, but that filename doesn't appear anywhere in the code you posted.
Without the actual code that is generating the actual error, it is impossible to answer your question. However, here are a few general tips:
Whenever the computer tells you that it cannot find something, in 99% of the cases, the problem is that the thing the computer tells it couldn't find isn't actually there.
So, in this case, the computer tells you that it cannot find a file named makRequire.rb, and the most likely explanation for that is that makRequire.rb doesn't actually exist. So, the first thing you need to check is: does makRequire.rb (note the capitalization and the file extension) actually exist? Because if it doesn't exist, then the reason why the computer cannot find it, should be rather obvious.
In 99% of the rest of the cases, the problem is that the thing the computer is looking for does exist, but the computer is looking in the wrong place. So, after you have verified that makRequire.rb actually does exist, you need to make sure that the directory the file is in, is in Ruby's $LOAD_PATH, and if it isn't, you need to add that directory to Ruby's $LOAD_PATH. Alternatively, if you want to require the file relative to the path of the file that is doing the requiring, you need to use require_relative instead of require.
The third thing to check for, is whether the user who own the ruby process has sufficient privileges to access the file makRequire.rb, the directory it is in and all of its parent directories.
Try this,
require File.join(File.dirname(__FILE__),'MarkModule')
Try require './MakModule', because the . is the current directory.
require 'MakModule'
You can require a file that is in the same directory. To use a module you would typically include the module inside a class definition. So you would never require Display, you would require the file that contains Display (without the .rb extension, usually).

Save WWW::Mechanize::File to disk using FileUtils

Using Mechanize with Ruby I get a certain file using agent.get('http://example.com/foo.torrent'), with FileUtils or otherwise, how do I save this file to my hard drive (for instance, in a directory wherefrom the script is running)?
P.S. class => WWW::Mechanize::File
Well, WWW::Mechanize::File has a save_as instance method, so I suppose something like this might work:
agent.get('http://example.com/foo.torrent').save_as 'a_file_name'
Please note that the Mechanize::File class is not the most appropriate for large files. In those cases, one should use the Mechanize::Download class instead, as it downloads the content in small chunks to disk. The file will be downloaded to where the script is running (although you can specify a different path as well). You need to set the default parser first, create a new one or modify an existing parser. Then, save it to the desired path:
agent.pluggable_parser.default = Mechanize::Download
agent.get( "http://example.com/foo.torrent}").save("path/to/a_file_name")
Check here and here for more details. Also, there's a similar question here in Stackoverflow.

Resources