Running A Sinatra Console
For the past couple of months I’ve been searching for (and bemoaning the lack of) a proper ‘console’ command in Sinatra to access my data. Rails has its aptly named rails console
command that allows you to quickly see things like User.all
or User.last
—but despite my best Googling, I’d found no such thing for Sinatra.
Well, today one of my beta testers forgot their password and asked me if there was a way to reset it. My immediate response was that I could do it… but I’d have to figure it out. The only way I’d been accessing my production data at this point was to log in directly to my Postgres database and issue SQL commands. However, all of my users’ passwords are stored as encoded strings so I wasn’t sure of the best way to encrypt the string and send it in…
I jumped into the terminal and typed heroku pg:psql
. Fortunately, I was faced with an 'update heroku toolbelt’ message that made me take a pause. Upgrading the heroku tools just to change a user’s password sounded like a trip down a rabbit hole, so I decided to see if I could at least just do a heroku run console
. That worked fine and I was faced with the familiar irb prompt.
My next thought was that if I could just require the file that had my DataMapper User model in it, via require './lib/datastore/dm_datastore/models/user'
… and then somehow require the proper DataMapper and Postgres adapter gems… and then configure the DB adapter to point to my heroku database… then I could use familiar DataMapper commands (which are similar to ActiveRecord).
But what was the easiest and safest way to do all the requiring of the proper files and set-up of the DB adapter?
And then I remembered that there’s already a file that has all of that set-up plus requires all the other files and gems the app the app needs…
Any guesses?
Of course, it’s my main Sinatra app file. In my case foundry.rb
. So after one simple require './foundry'
in irb I had access to all the familiar DataMapper commands and access to my data to easily do what I needed to.
This works locally as well. If I open up irb while in my app directory, then just require the main app file, I can poke around whichever repository I happen to be using.
So yeah, there’s a Sinatra console- it was right in front of me the whole time:
$: irb
irb > require './yourappfile.rb'
*should return true*
irb > *and you're in*