Skip to content

Instantly share code, notes, and snippets.

@stevenklise
Created April 18, 2013 19:34
Show Gist options
  • Save stevenklise/5415589 to your computer and use it in GitHub Desktop.
Save stevenklise/5415589 to your computer and use it in GitHub Desktop.
Using `irb` to connect to a Sinatra app or DataMapper connection
# require basic libraries
source 'https://rubygems.org'
require 'rubygems'
require 'sinatra'
require 'data_mapper'
# require DataMapper adapter, in this case we'll use Postgres
require 'dm-postgres-adapter'
DataMapper.setup(:default, ENV['DATABASE_URL'])
class Shape
include DataMapper::Resource
property :id, Serial
property :name, String, :length => 255
property :sides, Integer
property :regular, Boolean, :default => false
end
DataMapper.finalize
DataMapper.auto_upgrade!
get '/' do
'hi!'
end
get '/shapes/:name' do
@shape = Shape.first(:name => params[:name])
"#{@shape.name} has #{@shape.sides} sides"
end

The file app.rb is a Sinatra app, really simple. But what if you want to interact with your database without Sinatra? Ruby has irb a program that lets you run ruby commands one line at a time. To start using irb open up Terminal and cd to the folder your app is in. Then type irb and hit enter. If you are trying to connect to Heroku use heroku run irb WARNING: changing data on Heroku will change it for your web app, so be sure you know what you are doing.

You'll notice the prompt changes to an angle bracket (>) from a dollar sign ($) or something.

First we need to require the ruby file containing our app:

> require './app'

We now have access to the code in the app. If you type

> shape = Shape.new

You'll get: => #<Shape @id=nil @name=nil @sides=nil @regular=nil> You've just made a new Shape object, it hasn't been saved to the database yet, let's give it some info and then save it to the database.

> shape.name = "square"
# => "square"
> shape.sides = 4
# => 4
> shape.regular = true
# => true
> shape.save
# => true

Now that we have a shape, let's get all of the shapes:

shapes = Shape.all

For further documentation check out http://datamapper.org/docs/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment