Ruby Sinatra - connect to mongoDB on mongoHQ failed - ruby

This is just for my weekend project/study, I am very new to Sinatra and MongoDB.
I've installed the gems for mongoDB, such as: mongo, mongo_mapper and mongoid.
When I tried connecting to my database on MongoHQ from localhost, it encountered such an error:
Mongo::ConnectionFailure at /
failed to connect to any given host:port
* file: connection.rb
* location: connect
* line: 489
I found a similar thread on SO, but frankly speaking, I don't quite understand the answers...
Here is my code snippet:
require 'rubygems'
require 'sinatra'
require 'mongo'
require 'mongo_mapper'
get '/' do
MongoMapper.connection = Mongo::Connection.new('flame.mongohq.com', 27044)
MongoMapper.database = 'notes'
MongoMapper.database.authenticate('foo', 'bar')
erb :list
end
I took the above code from here, but it seems not working...
Which part is wrong? Is there another way to do this? In the end this test web app will be deployed onto heroku, so I hope the solution can work with both localhost and my heroku server.
Updated:
I just created a minimal code snippet to test the mongodb connection:
require 'rubygems'
require 'mongo'
db = Mongo::Connection.new("flame.mongohq.com", 27044).db("notes")
But still got the error, after timeout:
$ ruby mongodbtest.rb
/Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:489:in
`connect': failed to connect to any given host:port (Mongo::ConnectionFailure)
from /Library/Ruby/Gems/1.8/gems/mongo-1.0.8/lib/../lib/mongo/connection.rb:137:in
`initialize'
from mongodbtest.rb:4:in `new'
from mongodbtest.rb:4
The hostname and port are according to mongoHQ documentation, so they must be right.
Thanks for the help in advance.
2nd Update:
I just tested the mongodb connection string using terminal:
mongo mongodb://flame.mongohq.com:27044/notes -u foo -p bar
Unfortunately this would get me an connection failed error, honestly, I don't know why...

I use
uri = URI.parse(ENV['MONGOHQ_URL'])
#mongo_connection = Mongo::Connection.from_uri( uri )
#mongo_db = #mongo_connection.db(uri.path.gsub(/^\//, ''))
#mongo_db.authenticate(uri.user, uri.password)
You can look up your mongo url using the heroku config --long command

Just gave this another try, this time, I was using the ip address taken from ping:
So, if I change :
db = Mongo::Connection.new('flame.mongohq.com', 27060).db("notes")
db.authenticate('fake', 'info')
To:
db = Mongo::Connection.new('184.73.224.5', 27060).db("notes")
db.authenticate('fake', 'info')
That will work...
I still don't understand why the domain name approach won't work, but at least I can finish this off :)

Related

Connecting to cloudant NoSQL database from ruby

I have trouble connecting to my cloudant NoSQL database hosted on bluemix with couchrest_model library.
I have similar code written in ruby which works just fine from my computer (running locally, no rails or sinatra):
require 'couchrest'
url = "https://blah-blah#url with credentials.com"
database_name = "testdb"
db = CouchRest.database!(url+"/"+database_name)
db.save_doc('_id':"dog",:name => 'MonthyPython', :date => Date.today)
doc = db.get('dog')
The code above successfully writes data to my database. However, when I tried to do similar thing with the newest 'couchrest_model' gem, I got the
/Users/userpruser/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=SSLv2/v3 read server hello A: unknown protocol (OpenSSL::SSL::SSLError)
I have viewed several pages, but with no luck. So what is the correct way to make it work with just ruby (no rails) or/and ruby+sinatra? I find this recipe http://recipes.sinatrarb.com/p/models/couchdb but I have no idea how to sed the evniroment variables and how to put it together.
Thanks for any help!
Did you try explicitly setting the port to 443 and the protocol to 'https'? See https://github.com/couchrest/couchrest_model#configuration
It looks like installing
gem install sinatra-config-file
and then requiring
require sinatra/config_file
solved my problem. Thanks to you all!

Ruby PG gem connection issue

I've searched several related posts for the issue I'm having but wasn't able to find an answer. I'm a student in a coding program where most people use Mac, but I'm on Windows ( 7, Pro, 64 ) - because of that I'm a bit locked in to the tools/software I'll post here.
I'm trying to open a connection through Ruby with the pg gem, and I'm using Sinatra and PostgreSQL. I've established the server, database, and configuration path variables for PostgreSQL, and I've successfully installed pg gem (didn't have an issue there as in some of the other posts) with the line:
gem install pg -- --with-pg-config=C:\Program Files\PostgreSQL\9.5\bin
So the problem is that when I boot up Sinatra and go to the localhost,
I get a NoMethodError, Undefined Method for nil:NilClass on a method that otherwise works for Mac users.
The method is:
configure :development do
set :db_config, { dbname: "news_aggregator_development" }
end
configure :test do
set :db_config, { dbname: "news_aggregator_test" }
end
def db_connection
begin
connection = PG.connect(Sinatra::Application.db_config)
yield(connection)
ensure
connection.close
end
end
get '/articles' do
#results = db_connection do |conn|
conn.exec("SELECT * FROM articles")
end
erb :index
end
connection returns nil, and so the close method returns with an undefined method error. I don't think there is a syntax error as I've checked with others regarding this, and I'm thinking it might be related to a connection error with pg.
First time post so please go easy on me =) Apologies if I've left out any needed information - let me know what more context could be helpful and I will try to provide it! Thank you!
Two points:
Wrap your Sinatra helpers in a helpers {} block. This will allow you to use settings.db_config instead of Sinatra::Application.db_config:
helpers do
def db_connection
connection = PG.connect(settings.db_config)
yield connection
ensure
connection.close
end
end
In your PG.connect call, you should pass the host, user, password, and any other options necessary for the pg gem to find, connect, and authenticate to your instance. The dbname alone is not enough—at least not on Windows.
configure :development do
set :db_config, {
host: "localhost",
port: 5432,
user: "foo",
password: "bar",
dbname: "news_aggregator_development"
}
end
Good luck!

Ruby Sinatra/Postgres - can't connect to heroku database with PG.connect?

I am trying to get a site set up on Heroku using Sinatra and PostgreSQL. It worked locally (connecting to local database), but after pushing it to Heroku and changing my PG.connect to reflect that, I get an Internal Server Error the moment a page tries to access the database.
require 'uri'
require 'pg'
uri = URI.parse(ENV['DATABASE_URL'])
def db(uri)
begin
connection = PG.connect(uri.hostname, uri.port, nil, nil, uri.path[1..-1], uri.user, uri.password)
yield(connection)
ensure
connection.close
end
end
I am pretty sure these are parsing correctly, because ENV['DATABASE_URL'] displays the full postgres://user:password#host:port/database information that I'm expecting, and if I do the same in IRB uri.hostname, ui.port, etc all return what's expected .
This is my first time trying to get a site working on Heroku, so I am not even sure how to troubleshoot this. (And I googled for about all of yesterday.)
Results for heroku pg:
=== DATABASE_URL
Plan: Hobby-dev
Status: Available
Connections: 0/20
PG Version: 9.4.2
Created: 2015-05-30 19:24 UTC
Data Size: 17.7 MB
Tables: 5
Rows: 9320/10000 (In compliance, close to row limit)
Fork/Follow: Unsupported
Rollback: Unsupported
And all the tables show up when when I do heroku pg:psql <database> from the cli.
Some answers I've seen said to add database.yml to my root app directory, so:
production:
adapter: 'postgresql'
database: '<database>'
host: ENV['DATABASE_URL']
username: '<username>'
There's probably something simple I'm missing, but I haven't seen a complete guide for Sinatra/PSQL on Heroku - nothing that goes specifically into setting up and connecting to your database. (Everything seems Rails-related.)
In your database.yml file you need to specify the correct host for the host entry. You are passing what is stored in DATABASE_URL (something like postgres://user:password#host:port/database) but it should just be the host.
You will also need to specify a port if it isn't the default for PostgreSQL.
Edit: should also point out if you plan to store the host (or anything else - you definitely should for username and password) in an environment variable you'll need to wrap it, e.g. <%= ENV['HOST'] %>, not just ENV['HOST'] (i.e. how you have in the database.yml excerpt above)

cannot connect to Postgres (pg) database from my Ruby Script using gem "pg"(This is not rails, just pure ruby)

I downloaded the postgres.app for my Mac OSX machine. I have a rails app that has connected and used the postgres DB that came with the postgres app.
Now I am writing a pure Ruby test script (Not Rails, pure Ruby, not even Active Record) to try to connect to the postgres database instance. These are the steps I followed to set this up
1) ran this command on the terminal:
gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/MacOS/bin/pg_config
2) Added this code to the test script:
#!/usr/bin/env ruby
#encoding: utf-8
require "pg"
#conn = PG.connect(
:dbname => 'oData',
:user => 'am',
:password => '')
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name character varying(255);");
I got this from this link
When I ran this script I get the following error:
/Users/am/.rvm/gems/ruby-2.0.0-p247/gems/pg-0.16.0/lib/pg.rb:38:in `initialize': could
not connect to server: No such file or directory (PG::ConnectionBad)
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
My Debug efforts:
My postgres.app is up and running.
I looked at the pg gem [documentation][2] and my syntax seemed OK.
The location of my postgres DB is entered in my bash script like so
PATH="/Applications/Postgres.app/Contents/MacOS/bin:$PATH"
Not sure what to do next. Any help would be appreciated, Thanks.
are you sure postgres is listening on a socket? are you sure the username and password is right?
I would be inclined to try something like
require 'pg'
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '')
puts "trying with tcp"
puts PG::Connection.ping(:dbname => 'oData',:user => 'am',:password => '', :port => 5432)
I used active record gem to make the connection work and it was fine
Settings to connect works for me.
But that code should look like
#conn.exec("CREATE TABLE programs (id serial NOT NULL, name
character(255))")

Sinatra heroku database access

I have a sinatra ruby app in heroku. I am trying to access the database via the console.When I run the heroku run console , I am getting the following error.
Running console attached to terminal... up, run.10
/app/vendor/ruby-1.9.2/lib/ruby/1.9.1/irb/init.rb:281:in `require':LoadError: no such file to load -- ./console.
When I try to access the record using the following command, I am getting the following error :
irb(main):001:0> Setting.first
NameError: uninitialized constant Object::Setting
from (irb):1
from bin/irb:12:in `<main>'
Can anyone help me in what needs to be done. Am I missing some file or Is there a different way to access the tables in heroku?
The heroku console thing is an old hack for rails apps, but it won't work elsewhere. As you can see from the output, it's trying to load a file called ./console. So, create a console file on your project root, and invoke IRB from it after having connected to your database. For example:
#!/usr/bin/env ruby
require 'irb'
require 'irb/completion'
require 'rubygems'
require 'bundler/setup'
# require something that connects to your database
# or just connect here using ENV['DATABASE_URL']
require 'your_project_setup'
IRB.start

Resources