Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

minor changes to run smoothly with latest gems #10

Merged
merged 1 commit into from

2 participants

cocoa Paul Dix
cocoa

Hi Paul. I send you some changes that may be of interest to run the example in chapter 1 with the latest version of the gems. Please review. Best regards.

Paul Dix pauldix merged commit 04cebcf into from
Paul Dix
Owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jul 5, 2012
This page is out of date. Refresh to see the latest.
3  chapter_01/.bundle/config
View
@@ -1,2 +1 @@
----
-BUNDLE_DISABLE_SHARED_GEMS: "1"
+--- {}
2  chapter_01/.rspec
View
@@ -0,0 +1,2 @@
+--color
+--format nested
14 chapter_01/Gemfile
View
@@ -1,14 +1,14 @@
source "http://rubygems.org"
# service
-gem 'activerecord', "=3.0.3"
-gem 'sqlite3', "=0.1.1"
-gem 'sinatra', "=1.1.0"
+gem 'activerecord'
+gem 'sqlite3'
+gem 'sinatra'
# client
-gem 'json', '=1.4.6'
-gem 'typhoeus', '=0.2.0'
+gem 'json'
+gem 'typhoeus'
# testing
-gem 'rspec', '=2.2.0'
-gem 'rack-test', '=0.5.6'
+gem 'rspec'
+gem 'rack-test'
91 chapter_01/Gemfile.lock
View
@@ -1,52 +1,57 @@
GEM
remote: http://rubygems.org/
specs:
- activemodel (3.0.3)
- activesupport (= 3.0.3)
- builder (~> 2.1.2)
- i18n (~> 0.4)
- activerecord (3.0.3)
- activemodel (= 3.0.3)
- activesupport (= 3.0.3)
- arel (~> 2.0.2)
- tzinfo (~> 0.3.23)
- activesupport (3.0.3)
- arel (2.0.4)
- builder (2.1.2)
- diff-lcs (1.1.2)
- ffi (0.6.3)
- rake (>= 0.8.7)
- i18n (0.4.2)
- json (1.4.6)
- rack (1.2.1)
- rack-test (0.5.6)
+ activemodel (3.2.6)
+ activesupport (= 3.2.6)
+ builder (~> 3.0.0)
+ activerecord (3.2.6)
+ activemodel (= 3.2.6)
+ activesupport (= 3.2.6)
+ arel (~> 3.0.2)
+ tzinfo (~> 0.3.29)
+ activesupport (3.2.6)
+ i18n (~> 0.6)
+ multi_json (~> 1.0)
+ arel (3.0.2)
+ builder (3.0.0)
+ diff-lcs (1.1.3)
+ ffi (1.0.11)
+ i18n (0.6.0)
+ json (1.7.3)
+ mime-types (1.19)
+ multi_json (1.3.6)
+ rack (1.4.1)
+ rack-protection (1.2.0)
+ rack
+ rack-test (0.6.1)
rack (>= 1.0)
- rake (0.8.7)
- rspec (2.2.0)
- rspec-core (~> 2.2)
- rspec-expectations (~> 2.2)
- rspec-mocks (~> 2.2)
- rspec-core (2.2.1)
- rspec-expectations (2.2.0)
- diff-lcs (~> 1.1.2)
- rspec-mocks (2.2.0)
- sinatra (1.1.0)
- rack (~> 1.1)
- tilt (~> 1.1)
- sqlite3 (0.1.1)
- ffi (>= 0.6.3)
- tilt (1.1)
- typhoeus (0.2.0)
- tzinfo (0.3.23)
+ rspec (2.10.0)
+ rspec-core (~> 2.10.0)
+ rspec-expectations (~> 2.10.0)
+ rspec-mocks (~> 2.10.0)
+ rspec-core (2.10.1)
+ rspec-expectations (2.10.0)
+ diff-lcs (~> 1.1.3)
+ rspec-mocks (2.10.1)
+ sinatra (1.3.2)
+ rack (~> 1.3, >= 1.3.6)
+ rack-protection (~> 1.2)
+ tilt (~> 1.3, >= 1.3.3)
+ sqlite3 (1.3.6)
+ tilt (1.3.3)
+ typhoeus (0.4.2)
+ ffi (~> 1.0)
+ mime-types (~> 1.18)
+ tzinfo (0.3.33)
PLATFORMS
ruby
DEPENDENCIES
- activerecord (= 3.0.3)
- json (= 1.4.6)
- rack-test (= 0.5.6)
- rspec (= 2.2.0)
- sinatra (= 1.1.0)
- sqlite3 (= 0.1.1)
- typhoeus (= 0.2.0)
+ activerecord
+ json
+ rack-test
+ rspec
+ sinatra
+ sqlite3
+ typhoeus
27 chapter_01/README
View
@@ -16,4 +16,29 @@ Note that you should be using the rspec command. It used to be spec, but with ne
You can run the client specs by opening up two terminal windows and putting the two commands in each:
ruby service.rb -p 3000
-rspec spec/client_spec.rb
+rspec spec/client_spec.rb
+
+#
+# NEW COMMENTS (cocoa)
+#
+
+Install RVM:
+curl -L https://get.rvm.io | bash -s stable --ruby
+
+Remove Gemfile.lock:
+rm Gemfile.lock
+
+Install the gems:
+bundle install
+
+Migrate the development and test databases:
+rake db:migrate SINATRA_ENV=test
+rake db:migrate SINATRA_ENV=development
+
+Run the service specs:
+rspec spec/service_spec.rb
+
+Run the client library specs. In 2 diferent terminals:
+ruby service.rb -e test -p 3000
+rspec spec/client_spec.rb
+
3  chapter_01/Rakefile
View
@@ -1,10 +1,7 @@
require 'rubygems'
-gem 'activerecord', "=3.0.3"
require 'active_record'
require 'yaml'
require 'logger'
-gem 'sqlite3', "=0.1.1"
-require 'sqlite3'
desc "Load the environment"
task :environment do
22 chapter_01/client.rb
View
@@ -1,5 +1,3 @@
-require 'rubygems'
-require 'bundler/setup'
require 'typhoeus'
require 'json'
@@ -17,10 +15,12 @@ def self.find_by_name(name)
end
end
- def self.create(attributes = {})
- response = Typhoeus::Request.post("#{base_uri}/api/v1/users", :body => attributes.to_json)
- if response.success?
- JSON.parse(response.body)["user"]
+ def self.create attributes
+ response = Typhoeus::Request.post("#{base_uri}/api/v1/users", :body => attributes.to_json )
+ if response.code == 200
+ JSON.parse(response.body)['user']
+ elsif response.code == 400
+ nil
else
raise response.body
end
@@ -28,8 +28,10 @@ def self.create(attributes = {})
def self.update(name, attributes)
response = Typhoeus::Request.put("#{base_uri}/api/v1/users/#{name}", :body => attributes.to_json)
- if response.success?
- JSON.parse(response.body)["user"]
+ if response.code == 200
+ JSON.parse(response.body)['user']
+ elsif response.code == 400 || response.code == 404
+ nil
else
raise response.body
end
@@ -37,12 +39,12 @@ def self.update(name, attributes)
def self.destroy(name)
response = Typhoeus::Request.delete("#{base_uri}/api/v1/users/#{name}")
- response.success?
+ response.success? # response.code == 200
end
def self.login(name, password)
response = Typhoeus::Request.post("#{base_uri}/api/v1/users/#{name}/sessions", :body => {:password => password}.to_json)
- if response.success?
+ if response.success? # response.code == 200
JSON.parse(response.body)["user"]
elsif response.code == 400
nil
5 chapter_01/models/user.rb
View
@@ -1,6 +1,9 @@
class User < ActiveRecord::Base
validates_uniqueness_of :name, :email
+ validates_presence_of :name, :email
def to_json
- super(:except => :password)
+ #super(:except => :password)
+ super(:except => [:password, :created_at, :updated_at])
+ #super(:only => [:name, :email, :bio])
end
end
76 chapter_01/service.rb
View
@@ -1,16 +1,33 @@
-require 'rubygems'
-require 'bundler/setup'
-
require 'active_record'
require 'sinatra'
-require "#{File.dirname(__FILE__)}/models/user"
+require_relative 'models/user.rb'
+require 'logger'
+
+# setting up a logger. levels -> DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
+log = Logger.new(STDOUT)
+log.level = Logger::DEBUG
# setting up our environment
env_index = ARGV.index("-e")
env_arg = ARGV[env_index + 1] if env_index
env = env_arg || ENV["SINATRA_ENV"] || "development"
+log.debug "env: #{env}"
+
+# connecting to the database
+use ActiveRecord::ConnectionAdapters::ConnectionManagement # close connection to the DDBB properly...https://github.com/puma/puma/issues/59
databases = YAML.load_file("config/database.yml")
ActiveRecord::Base.establish_connection(databases[env])
+log.debug "#{databases[env]['database']} database connection established..."
+
+# creating fixture data (only in test mode)
+if env == 'test'
+ User.destroy_all
+ User.create(
+ :name => "paul",
+ :email => "paul@pauldix.net",
+ :bio => "rubyist")
+ log.debug "fixture data created in test database..."
+end
# the HTTP entry points to our service
@@ -20,7 +37,7 @@
if user
user.to_json
else
- error 404, "user not found".to_json
+ error 404, {:error => "user not found"}.to_json # :not_found
end
end
@@ -28,29 +45,33 @@
post '/api/v1/users' do
begin
user = User.create(JSON.parse(request.body.read))
- if user
+ if user.valid?
user.to_json
else
- error 400, "" # do nothing for now. we'll cover later
+ error 400, user.errors.to_json # :bad_request
end
rescue => e
- error 400, e.message.to_json
+ error 400, {:error => e.message}.to_json
end
end
# update an existing user
put '/api/v1/users/:name' do
- user = User.find_by_name(params[:name])
+ user = User.find_by_name(params['name'])
if user
begin
- user.update_attributes(JSON.parse(request.body.read))
- # we don't have any validations right now. we'll cover later
- user.to_json
+ attributes = JSON.parse(request.body.read)
+ updated_user = user.update_attributes(attributes)
+ if updated_user
+ user.to_json
+ else
+ error 400, user.errors.to_json
+ end
rescue => e
- error 400, e.message.to_json
+ error 400, {:error => e.message}.to_json
end
else
- error 404, "user not found".to_json
+ error 404, {:error => 'user not found'}.to_json
end
end
@@ -61,7 +82,7 @@
user.destroy
user.to_json
else
- error 404, "user not found".to_json
+ error 404, {:error => 'user not found'}.to_json
end
end
@@ -69,14 +90,31 @@
post '/api/v1/users/:name/sessions' do
begin
attributes = JSON.parse(request.body.read)
- user = User.find_by_name_and_password(
- params[:name], attributes["password"])
+ user = User.find_by_name_and_password(params[:name],attributes['password'])
if user
user.to_json
else
- error 400, "invalid login credentials".to_json
+ error 400, {:error => 'invalid user or credentials'}.to_json
end
rescue => e
- error 400, e.message.to_json
+ error 400, {:error => e.message}.to_json
end
+end
+
+
+#
+# HELPERS
+#
+
+def show_request(request,log)
+ log.debug "request.request_method: #{request.request_method}"
+ log.debug "request.body: #{request.body}"
+ #log.debug "request.cookies: #{request.cookies}"
+ #log.debug "request.env: #{request.env}"
+ log.debug "request.content_length: #{request.content_length}"
+ log.debug "request.media_type: #{request.media_type}"
+end
+
+get '/foo' do
+ show_request(request, log)
end
19 chapter_01/spec/client_spec.rb
View
@@ -1,4 +1,5 @@
-require File.dirname(__FILE__) + '/../client'
+#require File.dirname(__FILE__) + '/../client'
+require_relative '../client.rb'
# NOTE: to run these specs you must have the service running locally. Do like this:
# ruby service.rb -p 3000 -e test
@@ -36,18 +37,22 @@
end
it "should create a user" do
- user = User.create({
- :name => "trotter",
- :email => "trotter@spamtown.usa",
- :password => "whatev"})
- User.find_by_name("trotter")["email"].should == "trotter@spamtown.usa"
+ random_name = ('a'..'z').to_a.shuffle[0,8].join
+ random_email = ('a'..'z').to_a.shuffle[0,8].join
+ user = User.create(
+ :name => random_name,
+ :email => random_email,
+ :password => 'whatev')
+ user['name'].should == random_name
+ user['email'].should == random_email
+ User.find_by_name(random_name).should == user
end
it "should update a user" do
user = User.update("paul", :bio => "rubyist and author")
user["name"].should == "paul"
user["bio"].should == "rubyist and author"
- User.find_by_name("paul")["bio"] == "rubyist and author"
+ User.find_by_name('paul').should == user
end
it "should destroy a user" do
6 chapter_01/spec/service_spec.rb
View
@@ -1,10 +1,10 @@
+ENV['SINATRA_ENV'] = 'test'
+
require File.dirname(__FILE__) + '/../service'
-gem 'rspec', '=2.2.0'
require 'rspec'
-gem 'rack-test', '=0.5.6'
require 'rack/test'
-set :environment, :test
+# set :environment, :test
#Test::Unit::TestCase.send :include, Rack::Test::Methods
RSpec.configure do |conf|
Something went wrong with that request. Please try again.