How to run a .rb file from IRB? - ruby-on-rails

I am starting out with Ruby on Rails. I am currently going through a tutorial where it says that I have to run a .rb file from IRB and that that will create a .xml file in my current directory.
My question is how do I run a .rb file in IRB?
And do I have to be in the directory where this .rb file lives when I run it in IRB?
I tried the following: just typing irb on the command line in the directory of the file. That starts an IRB session as far as I understand.
Then I typed irb "filename.rb" which went through but didn't create anything in the current directory but at least it didn't give any errors.
I also tried a whole bunch of other stuff that plain gave me errors. So I don't think I can solve this myself and googling the matter didn't help at all.
I am running Leopard.

You can "run" a file in irb by just requiring or loading it.
$ irb
>> load './filename.rb'
To change your current working directory within irb, you can use FileUtils:
>> require 'fileutils'
>> FileUtils.pwd # prints working directory
>> FileUtils.cd '/path/to/somewhere' # changes the directory

In case you want to have your file loaded in the irb session and you are using Ruby 2+ you can load a file in irb like this:
irb -r ./the_name_of_your_file.rb
This opens an irb session with the given file loaded.
Imagine you have file with a class like this:
class Example
def initialize(name)
#name = name
end
def print__example
p name
end
end
You will be able to use the Example class in the irb session.

We can just create a .rb file in the directory which you are currently working in using any text editor and type all the code in that and then use the command ruby filename.rb in the terminal, not in the irb, then it shows the output in irb.

Related

Possible to configure rails to load per project .irbrc file?

Can rails load .irbrc from the rails project root such as ~/rails-projct/.irbrc. Rather then ~/.irbrc. Since it would be nice to add configuration that's specific to a project.
Per the docs:
IRB reads from ~/.irbrc when it's invoked.
If ~/.irbrc doesn't exist, irb will try to read in the following order:
.irbrc
irb.rc
_irbrc
$irbrc
Meaning that this is possible, but only if you don't have a .irbrc file in your home directory. Tested and confirmed in Ruby 2.7.
If that's not possible, you'll have to rely on command line options and/or environment variables.

How to set up a file that I can run through my command line?

I am using Sublime Text and Ruby on Rails. Everything is installed.
How do I set up a file like random.rb
that I can navigate to in my git bash and run its contents.
The main reason I want to do this is to play with classes, methods and functions and see their outputs. IRB is not enough for when I want to build entire functions, etc.
How would I go about achieving this?
First example: simply run your Ruby code from the IRB prompt:
$ irb
> puts 'playing in irb prompt'
Second example: write your Ruby code to a ".rb" file and run it by using ruby file_name.rb:
#test.rb
puts 'Hello World'
$ ruby test.rb
-> "Hello world"
Third example: from Rails' console, you can run your .rb file:
$ rails console
$ eval(File.read 'test.rb')
-> 'Hello world'
#make sure your test.rb file resides in your project root directory.
Fourth example: use rails console to interact with your application model:
$ rails console
$ User.all #depending on what model you have.

How to run Ruby scripts in Command Line?

I've installed Jekyll and I'm trying to import a simple CSV file with a few posts. I've never used Ruby before. In Jekyll's import docs it shows the following code that needs to be run via Command Line.
http://import.jekyllrb.com/docs/csv/
$ ruby -rubygems -e 'require "jekyll-import";
JekyllImport::Importers::CSV.run({
"file" => "my_posts.csv"
})'
I'm I supposed to type the whole thing into Command Line and run it or is the first line supposed to call a function that includes the last three lines of code?
Sorry for the noob question but I really couldn't find any answers to this.
Thanks
You can put scripts in a file with a .rb extension and run it with:
ruby import_csv.rb
Your file import_csv.rb would contain:
#!/usr/bin/env ruby
require "jekyll-import";
JekyllImport::Importers::CSV.run({
"file" => "my_posts.csv"
})
I think the -rubygems switch is not needed since it is enabled by default. If not, add the line require rubygems before the other require line.
Just put your codes in a file with rb extension, it should be something like this,
require 'rubygems'
require "jekyll-import"
JekyllImport::Importers::CSV.run({
"file" => "my_posts.csv"
})
Lets say file name sample.rb. Then run this file using the following command,
ruby sample.rb
Use IRB console by typing irb at command prompt

.bashrc equivalent for rails console?

When I'm using the rails console I like having a clear! command along side the reload! command, so every time I launch the rails console I write
def clear!
system('clear')
end
When I repeat behavior in my bash shell I add it to my ~/.bashrc file. Is there a similar way for me to do this for my rails console?
Create a file in your home directory named ~/.irbrc. Inside, define any functions or settings you want to be applied to your irb.
Here's an example that explains what I mean.
You can do this with Pry if you use that instead of irb. You can configure custom commands in a ~/.pryrc
Pry.config.commands.command "clear!", "Clears the display" do |*args|
system("clear")
end
See pry-rails

automatically load project's environment to irb

Rails has useful command rails console, which downloads all necessary data and then we can interact with rails project in irb. Is there the same technique for Ruby project (built on Ruby language)? By this trick I can play with Ruby project in the irb without concerning about loading libraries, modules, classes, files and so on.
Thanks
Your project should have one file which loads the environment. Assuming your project is in lib/project.rb then simply:
$ irb -Ilib -rproject
From one of my projects:
# Creates an IRB console useful for debugging experiments
# Loads up the environment for the condition passed
def console
File.open("./tmp/irb-setup.rb", 'w') do |f|
f.puts "# Initializes the environment for IRb."
f.puts "Code to initialize your project here"
f.puts "$: << '#{File.expand_path(".")}/'" #handle load path
end
irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
# require your code
libs = " -r irb/completion"
libs << " -r #{File.dirname(__FILE__) + "/base"}"
libs << " -r ./tmp/irb-setup.rb" # require the config file you just wrote
puts "Loading #{#options.env} environment..."
exec "#{irb} #{libs} --simple-prompt"
end
The trick is that you construct the irb command to autorequire all the code you need. I also needed to set up some configuration so I add the magick of writing a file I then require in IRb.
In my case my initialization script was in the current working directory. The below worked for me.
irb -r ./setup.rb

Resources