Automatically load Dotenv on my ruby console - ruby

I'd like to automatically run Dotenv.load('.env.development') whenever I launch up a ruby console, it could either be from bundle console or alternatively irb. I'm using Sinatra, not Rails, and I'm not sure how to run some commands on console start.. I'd prefer to do this without a bash script, instead using the internal capabilities of the tools.. If there's a place to put ruby code on the start of a ruby console that would solve my issue and also allow for future console customization.

You can create a .irbrc file in our project's directory which is loaded automatically when an IRB session is started. And add something like this to that file:
begin
require 'dotenv'
Dotenv.load('.env.development')
rescue => e
puts "loading Dotenv failed. because: #{e.message}"
end
Read more about the .irbrc file in the Ruby-Docs.

You try folliwing the documentation of gem(sorry my ignorance I don't know anything about sinatra)?:
Documentation dotenv
Install the gem:
$ gem install dotenv
By default, load will look for a file called .env in the current working directory. Pass in multiple files and they will be loaded in order. The first value set for a variable will win.
require 'dotenv'
Dotenv.load('file1.env', 'file2.env')
In your case i think should be:
require 'dotenv'
Dotenv.load('.env.development')
In ruby vanilla I dont know if possible, I think yes.

One option is to creating a ./bin/console script ala Bundler's gem.
I created this bin/console file as a temporary solution, but I'm curious whether I can get #spickermann's answer (which I incorporated here) with irbrc to work with a same-directory .irbrc
#!/usr/bin/env ruby
begin
require 'dotenv'
Dotenv.load('.env.development')
rescue => e
puts "loading Dotenv failed. because: #{e.message}"
end
require "irb"
IRB.start(__FILE__)

Related

How to use pry-byebug in an example script for a gem?

I'm working on making my first gem, which is not a Rails app, is a tic-tac-toe library with some AI in it, so I can play a computer opponent that will never lose and force a win if possible.
Right now I am trying to debug the attack strategy in the AI, but I can't seem to figure out how to get pry-byebug working in my test script, specfically, have the debugging commands like step, next, etc. work upon hitting a binding.pry.
The gem, named smart-tac-toe, has the following directory structure:
$ ls smart-tac-toe
example Gemfile Gemfile.lock Guardfile lib LICENSE.txt Rakefile README.md smart_tac_toe.gemspec spec tmp
As you can see above, there is an 'example' directory in my gem which contains "example.rb", where I use the classes I've made.
However, when I use binding.pry and try to use step and next, the Pry session just exits and the script keeps running.
In my smart_tac_toe.gemspec file, I clearly have pry-byebug:
spec.add_development_dependency "pry-byebug", '~>2.0.0'
and at the top of my example.rb file, I have tried requiring the proper gems:
require 'pry'
require 'pry-byebug'
require "../lib/smart_tac_toe.rb"
I am using Ruby 2.1.1p76 , the repo for this gem is located at https://github.com/discotroll65/smart_tac_toe
Also, though putting binding.pry into my example script does throw me into a debugging session, initially it is in a reading mode, and I have to press q to exit that before I can start doing repl stuff. Any thoughts as to why this may be?
Ok, looking into this more I realized (I think...still kind of new to the game) a couple things --
1.) If you want to if have
require 'pry'
at the top of your ruby file and have it work in general, it would help to install it in your development environment using your terminal:
user#machine/currentdirectory/$ gem install pry
likewise with pry-byebug:
user#machine/currentdirectory/$ gem install pry-byebug
2.) The real answer to my initial question is to use
byebug
in my script as the debugging hook, instead of
binding.pry
(thanks #mtm for the suggestion!)
when I do use byebug though, while step and next work properly, the REPL it throws me into doesn't have any color, and isn't as nice in general...anyway to fix that?
I think you're overdoing it. This works for me:
require 'pry-byebug'
puts 'foo'
binding.pry
puts 'bar'

Rails -- is IRB necessary?

I am following Michael Hartl's RoR toturial and there are multiple places where he uses IRB, often to add users to the database. When I use rails console to open IRB and then create a User in the database everything works fine, but if I try to do the same thing by running the same line of code from a file like test.rb in the directory of my application it doesn't work b/c it says it can't find the User model. Is there any way I can run these lines of code (i.e. for putting a user into a database) from a .rb file rather than from the IRB?
For a separate script look into rails runner. It loads the Rails backend so you have access to all the models and exists for this purpose.
From the "Ruby on Rails Guides":
runner runs Ruby code in the context of Rails non-interactively. For instance:
$ rails runner "Model.long_running_method"
If you're just using test.rb as a convenience to save and re-run console commands, you could do this:
rails console < test.rb
Or, as a bit of a hack, put this at the top of your test.rb:
require 'config/environment'
And invoke it from the app's root directory like this:
ruby -I . test.rb
Placing a ruby file in the folder of your app doesn't automatically load up your Rails app. You need to explicitly load the config/environment.rb file to load the Rails app.
If your test.rb is in the root of your app, you can do something like
require File.expand_path("../config/environment", __FILE__)
# Access your models here

Sinatra cannot find views on Ruby 1.9.2-p0

I'm quite new to Ruby language (up to now I developed in Groovy + Grails) but since I was curious about it I wanted to try Sinatra on Ruby 1.9.2-p0.
I have a trivial website that is contained in /mywebpage and has 2 files:
# blog.rb
get '/' do
'Hello World!'
end
get '/impossible' do
haml :index
end
and
#config.ru
path = File.expand_path "../", __FILE__
$LOAD_PATH << (File.expand_path ".") + "/views"
require 'haml'
require 'sinatra'
require "#{path}/blog"
run Sinatra::Application
then in the same folder I have a /views/ folder that contains index.haml.
I try to run the server with rackup -p8080 but when I try to get /impossible I receive the following error:
Errno::ENOENT at /impossible
No such file or directory - /home/jack/mywebpage/<internal:lib/rubygems/views/index.haml
By searching over internet it seems that this maybe caused by "." not being included in $LOAD_PATH so I tried to add it or add directly views ./views so that actually $LOAD_PATH.inspect gives me correct path: ..., "/home/jack/mywebpage/views"]
But still it doesn't seem to work. Being quite new to the framework and the language I was wondering if I'm doing something wrong. any clues?
Running Sinatra with Ruby 1.9.2 the template directory is no longer implicitly 'views', you need to set it yourself.
set :views, File.dirname(__FILE__) + "/views"
Note that currently Ruby also has Kernel#__dir__() method that is equivalent to File.dirname(__FILE__).
This, and other issues with 1.9, will be have been solved in Sinatra 1.1. You could use this fork: http://github.com/rkh/sinatra/tree/1.1
I ran into a similar problem, and solved it like this. I didn't dig into the problem, but this is what I found and it works. It'll supposedly be fixed in the next version of Sinatra (which they should really get out the door, just to fix these few 1.9.2 bugs).
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
enable :run
get '/' do
"Hello, world!"
end
Edit: It seems there are multiple bugs with Sinatra on 1.9.2. This one will fix Sinatra apps not starting on 1.9.2. I don't use a views directory (I like to keep my apps single-file), so I didn't run into your particular problem. This fix most likely won't help you at all. I probably should have read your problem more closely..
gem install sinatra --pre
I ran into that last week and didn't find a suitable fix on the Sinatra site short of tweaking the sinatra code. I'm using rvm for my development and switched to try sinatra on Ruby 1.8.7 and it works fine again, so that's where I left it.
Oh, since you're new to Ruby, you might not know about rvm, so here's the lowdown. RVM is Mac only and highly recommended for managing your Ruby version and gems. It makes it trivial to have multiple Ruby versions and alternate groups of gems for development and testing. Everything is stored in your ~/.rvm directory so it's easy to blow it all away if you need to.
http://rvm.beginrescueend.com/
I just looked at the Sinatra site again about the problem to see if there was anything new, but it appears they consider the following to be an acceptable fix:
http://github.com/sinatra/sinatra/issues/#issue/50
I'm a bit adverse to having to edit the source of Sinatra as recommended by issue #50, but it's not real hard to do. I'd like to see them put out an update so we'd have an official fix but I haven't seen anything yet:
gem env will tell you the "GEM PATHS". Sinatra's gem will be in one of those. The line mentioned in issue #50 goes into base.rb. On my machine it's something like ...gems/ruby-1.9.2-p0/gems/sinatra-1.0/lib/sinatra/base.rb.
Insert:
/<internal:/, # ruby 1.9.2-p0 hacks
at line 1020.
Save the file and you should be good to go.

Ruby "No Such File To Load - sqlite3" on OS X

I was trying to create a quick little script that would insert data into an SQLite db for me but I can't get past the first few steps.
I have done "sudo gem install sqlite3-ruby", my Ruby version is 1.8.7 (I used the Ruby one click installer from rubyforge.org).
My script is incredibly simple. It looks like this:
#!/usr/bin/ruby -w
require "csv.rb"
require "sqlite3"
begin
CSV.open('updateddata.sql', 'r') do |row|
p row
end
rescue => err
puts "Exception : #{err}"
err
end
It never makes it past the line require "sqlite3". It just errors and tells me that it can't find that file to load.
I don't understand how it won't work even after using the One click installer (which is supposed to have SQLite built into the install).
I'm not even sure where to go from here.
I am not a Ruby developer at all, I just wanted to use it as a learning experience and to quickly complete this task for myself.
Dunno if Ruby in OS X behaves differently, but normally you need to do require 'rubygems' before requiring any gems.
You can also add
export RUBYOPT=rubygems
to your profile.
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/43fc65132487f98e/?pli=1 using sqlite3-ruby gem solved my issue on this

(...)in `require': no such file to load -- 'gemname' (LoadError)

I haven been all day training to fix this problem but i couldn't.
The question is easy, i don't want to put anymore the require 'rubygems' line everytime i require a gem...
If i put the require 'rubygems' before any other "require" the file runs perfect but if i don't put the require 'rubygems' line the following error occurs:
(...)in `require': no such file to load -- 'gemname' (LoadError)
I suspect that may be there is some path remaining where to check out the gems repository.
I want to ask you if there is a way to do this.
Thanks a lot.
Cheers,
Juan.
You could invoke you ruby script with
ruby -rubygems script.rb
or add rubygems to RUBYOPT
$ export RUBYOPT="rubygems"
put
require 'rubygems'
as first line of your ruby code and be safe.
of course you can invoke with -rubygems switch (as Peter Krenn wrote) instead of it
In Unix you can:
$ RUBYOPT="rubygems"
$ export RUBYOPT
$ ruby juans_masterpiece.rb
and in Windows:
SET RUBYOPT=rubygems
or right-click on My Computer->Properties->Advanced->Environment Variables
and then finally add the RUBYOPT variable there. Next time you open a cmd.exe run set and it will be there.
You don't have to put it every time you require a gem — you just have to have it before the first time you require a gem. When you require Rubygems, it replaces the default require with a special one that does all the Rubygems magic.
But that's only in 1.8. You don't have to require Rubygems at all in Ruby 1.9 — so that's a very easy solution to the problem as long as you aren't dependent on 1.8-specific things.
Right-click the Computer Icon, then select Properties, then Additional system parameters, then Environment variables, there is a GUI for changing opts, click Create, put name and value, OK. This is an approximate translation of how you do this on windows 7, if you can't find the place try to google for "changing environment variables in {your windows version here}"

Resources