Firefox can't establish a connection to the server at localhost:4567 - ruby

I created a simple ruby/sinatra application following a tutorial from tutsplus. I have done everything as instructed but when I go to "localhost:4567", I don't see what I expect, instead I am greeted with the error message:
"Firefox can't establish a connection to the server at localhost:4567"
Is there something I need to do to this port?
EDIT:
With some help i figured I should have used port 9393. But now i get this error: error
and this is the code in my recall.rb app:
require 'rubygems'
require 'sinatra'
require 'datamapper'
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/recall.db")
class Note
include DataMapper::Resource
property :id, Serial
property :content, Text, :required => true
property :complete, Boolean, :required => true, :default => false
property :created_at, DateTime
property :updated_at, DateTime
end
DataMapper.finalize.auto_upgrade!
get '/' do
#notes = Note.all :order => :id.desc
#title = 'All Notes'
erb :home
end
EDIT again:
SOLVED using
require data_mapper

According to the png file you posted in your other comment, your Webrick server is saying it started up on port 9393. So you should try accessing the app via http://localhost:9393.

Remember to start your server with shotgun recall.rb.

Related

Sinatra with Datamapper throws undefined method `add_domain_type' for Psych:Module (NoMethodError)

I'm working on a pretty simple sinatra + datamapper app, and it was launching and working just fine yesterday. I attempted to introduce some seed data into the db, and started getting this strange error on launch. I reverted back to pre-seed code, and the error persists. I've noticed that commenting out the include DataMapper::Resource in my model makes the app run again. here's the error:
/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/dm-serializer-1.2.2/lib/dm-serializer/to_yaml.rb:15:in included': undefined methodadd_domain_type' for Psych:Module (NoMethodError) ... Any ideas?
#app.rb:
require 'sinatra'
require 'pry'
require_relative 'models'
helpers do
def content_path(file)
File.join("images", file)
end
end
get '/' do
#photos = Photo.all
erb :index
end
models.rb
require 'data_mapper'
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/db/photos.db")
class Photo
include DataMapper::Resource
property :id, Serial
property :created_at, DateTime
property :title, String
property :body, Text
property :filename, String
property :description, Text
property :width, String
property :height, String
end
DataMapper.finalize
Photo.auto_upgrade!
EDIT: It appears that upgrading ruby to 2.2.0 and reinstalling the gems solved the problem

How do I export data from CSV to DataMapper in Sinatra?

I'm building a simple web application using Sinatra.
I have an external text file and would like to parse it using CSV. Then I would like to export the data and create a database using DataMapper. I'm stuck on how to accomplish this.
This is what I have so far:
require 'sinatra'
require 'csv'
require 'data_mapper'
CSV.foreach("words.txt") do |row|
puts row[0]
end
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/scrabble.db")
class Letters
include DataMapper::Resource
property :id, Serial
property :content, Text, :required => true
property :created_at, DateTime
property :updated_at, DateTime
end
Can anyone point me to the right direction?
if you itterate through a list of words, you need to do like that:
require 'sinatra'
require 'csv'
require 'data_mapper'
DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/scrabble.db")
class Letters
include DataMapper::Resource
property :id, Serial
property :content, Text, :required => true
property :created_at, DateTime
property :updated_at, DateTime
end
CSV.foreach("words.txt") do |row|
Letters.create(content: row[0])
end

In Ruby/Sinatra, Datamapper's .all works but .get doesn't?

I am trying to take data from a path in Sinatra, and use it to look up a particular record using Datamapper. The Datamapper docs seem to indicate that.
get "/test/:test_path" do
test_get = Intake.get( params[:test_path] )
# Do stuff
erb :blah_blah_blah
end
should find any records associated with the symbol :test_path
This does not work. test_get gets nil.
Meanwhile, what does work is
get "/test/:test_path" do
test_all = Intake.all(:test_path => params[:test_path] )
# Do stuff
erb :blah_blah
end
My two questions are:
What am I doing wrong with the .get() call in Datamapper?
Is the .all(:name => value) method slower than .get(), or does it not matter which I use?
Here's a Sinatra script pared down to demonstrate the behavior.
#!/usr/bin/env ruby
require 'rubygems'
require 'sinatra'
require 'dm-core'
require 'dm-timestamps'
DataMapper.setup(:default, {:adapter => 'yaml', :path => 'db'})
class Intake
include DataMapper::Resource
property :id, Serial
property :created_at, DateTime
property :test_path, String
end
get "/test/:test_path" do
test_all = Intake.all(:test_path => params[:test_path] )
puts 'test_all:' test_all.inspect
test_get = Intake.get( params[:test_path] )
puts 'test_get:' test_get.inspect
"Hello World!"
end
#get only does a lookup based on primary key, with is the id. So
Intake.get(params[:test_path])
looks for something with id params[:test_path], which will fail. Use
Intake.first(test_path: params[:test_path])

"No tests." error in ruby unit tests

My original test for user.rb looks like this:
require "test/unit"
require "minitest/autorun"
require "rack/test"
require_relative "../lib/kimsin.rb"
ENV['RACK_ENV'] = 'test'
class UserTests < Test::Unit::TestCase
include Rack::Test::Methods
include Kimsin
def app
Sinatra::Application
end
def test_user
#user = User.create :username => "barerd", :password => "abcdef"
get "/users"
assert_equal #user.username, "barerd"
refute_match #user.password, "abcdef"
end
end
The test ran and obviously failed as there was no User class. When I added the User class like below:
module Kimsin
require "data_mapper"
require "dm-migrations"
DataMapper.setup :default, "sqlite:///users.db"
class User
include DataMapper::Resource
include BCrypt
property :id, Serial
property :username, String, :required => true
property :password, String, :required => true
property :salt, String, :default => "876587349506434245565664566"
property :crypto, String, :default => BCrypt::Password.create password + salt
end
User.auto_migrate!
end
it throws a "No tests." error. Actually, not only this one but all tests throw the same error now. I suspected that this has sth to do with ruby in general, because it happened after I gem installed dm-core and at the beginning it threw an error:
"Error loading RubyGems plugin "/home/barerd/.rvm/gems/ruby-1.9.3-p125/gems/rubygems-bundler-0.2.8/lib/rubygems_plugin.rb": cannot load such file -- rubygems_bundler/rubygems_bundler_installer (LoadError)"
But when I try to run tests of other apps, they all work fine.
I use rvm 1.11.6 (stable) and ruby 1.9.3p125 (2012-02-16 revision 34643) [i386-cygwin] on a windows 7 by the way. Any clue to the error?
To note, the core module file kimsin.rb is as follows:
require "sinatra"
require "erb"
require "bcrypt"
require_relative "../lib/kimsin/version"
require_relative "../lib/kimsin/user"
use Rack::Session::Pool, :expire_after => 2592000
set :session_secret, "n9c0431qt043fcwo4ponm3w5483qprutc3q9pfw3r0swaypedx2qafec2qdomvuj8cy4nawscerf"
module Kimsin
get "/" do
title = "Kimsin?"
erb :index, :locals => {:title => title}
end
end

Sinatra/CouchDB error?

I'm working on my first Sinatra/CouchDB project and I'm getting an error I can't explain.
Here's my rackup (config.ru) file:
require 'rubygems'
require 'couchrest'
require 'patina'
set :environment, :development
set :root, File.dirname(__FILE__)
set :run, false
FileUtils.mkdir_p 'log' unless File.exists?('log')
log = File.new("log/sinatra.log", "a")
$stdout.reopen(log)
$stderr.reopen(log)
set :db, CouchRest.database!("http://127.0.0.1:5984/test")
run Sinatra::Application
And here's the app file (patina.rb):
require 'rubygems'
require 'sinatra'
require 'couchrest'
require 'haml'
class Article < CouchRest::ExtendedDocument
use_database settings.db
property :title
timestamps!
view_by :title
end
get '/' do
#db = settings.db
haml :index
end
Without the class definition in patina.rb, the route returns a page that displays the #db property as I was expecting. However, when I add the class definition to patina.rb I get "Ruby (Rack) application could not be started" error message.
Obviously this has something to do with my class definition, but I can't figure out what the problem is and the error message doesn't seem that helpful to me.
Also, I'd actually prefer to have the class definition in a separate file (Article.rb), but I can't figure out how to do that in the context of my Sinatra app.
Any help would be greatly appreciated!
EDIT:
See my answer below.
After a lot of googling, I discovered that the 1.4 series of json.gem are known to cause a lot of problems. I uninstalled all the json gems I had and installed json-1.2.4.gem instead. I have everything working correctly now. Here's the setup I'm using:
config.ru (Rackup file):
require 'application'
set :environment, :production
set :root, File.dirname(__FILE__)
set :run, false
FileUtils.mkmdir_p 'log' unless File.exists?('log')
log = File.new('log/sinatra.log', 'a+')
$stdout.reopen(log)
$stderr.reopen(log)
run Sinatra::Application
environment.rb:
require 'rubygems'
require 'couchrest'
require 'haml'
require 'ostruct'
require 'sinatra' unless defined?(Sinatra)
configure do
SiteConfig = OpenStruct.new(
:title => 'Application Title',
:author => 'Your Name',
:url_base => 'Your URL',
:url_base_db => 'Your CouchDB Server',
:db_name => "Your DB Name"
)
# load models
$LOAD_PATH.unshift("#{File.dirname(__FILE__)}/lib")
Dir.glob("#{File.dirname(__FILE__)}/lib/*.rb") { |lib| require File.basename(lib, '.*') }
end
lib/contact.rb (Model example, models auto-loaded in environment.rb):
class Contact < CouchRest::ExtendedDocument
include CouchRest::Validation
use_database CouchRest.database!((SiteConfig.url_base_db || '') + SiteConfig.db_name)
property :name
timestamps!
view_by :name
end
application.rb:
require 'rubygems'
require 'sinatra'
require 'environment'
configure do
set :views, "./views"
end
error do
e = request.env['sinatra.error']
Kernel.puts e.backtrace.join("\n")
'Application error'
end
helpers do
end
get '/new/?' do
haml :new
end
post '/save/?' do
#contact_name = params[:contact_name]
#contact = Contact.new
#contact.name = #contact_name
#contact.save
haml :save
end
get '/' do
haml :index
end
Hope this helps someone in the future!
try requiring 'patina' after setting :db. I think the class body of Article is executing the use_database method before the setting exists.
you should be able to put Article in article.rb (ruby naming convention is UpperCamel for classes, but under_scores for the files in which classes are defined) and then require 'article' in patina.rb.
thats the only thing that stood out for me, so let me know if that works.

Resources