Showing posts with label sinatra. Show all posts
Showing posts with label sinatra. Show all posts

Friday, October 16, 2009

Smoke 'em If You Got 'em

‹prev | My Chain | next›

I did a quick push to the beta site this morning so that I could do some smoke testing. For the most part, everything looked good. Sadly, I did discover another oversight in my switch of the recipe URL delimiter from dashes to slashes. The recipe search results still had the dashes in them.

I am somewhat disappointed that my Cucumber scenarios did not catch this error. It would have been a simple matter of one of the 10 recipe search scenarios following a link from the search results to the actual recipe. A simple matter indeed, but I did not include such a step.

This is, of course, the point of smoke tests. Even if you have awesome tests, even if you do not make big changes the day before deploying, it is always a good idea to poke around. There may be a bit of smoke, there may be a raging inferno, but you won't know unless you exercise the code.

After fixing the link in the search results (a minor code change, but involving many spec changes), I am ready to deploy. But first...

I am not certain that I have identified the last of the dash/slash issues. Rather than delay the promotion to production, I do a bit of defensive Rack configuration with Rack::Rewrite. Specifically, a recipe URL that contains dashes should be redirected to the proper slash URL:
use Rack::Rewrite do
r301 %r{(.+)\.html}, '$1'
r301 %r{^/recipes/(\d{4})-(\d{2})-(\d{2})-(.+)}, '/recipes/$1/$2/$3/$4'
end
The curl command verifies that this works:
jaynestown% curl -I http://localhost:3000/recipes/2008-07-13-sausage   
HTTP/1.1 301 Moved Permanently
Location: /recipes/2008/07/13/sausage
Content-Length: 14
Connection: keep-alive
Server: thin 1.2.2 codename I Find Your Lack of Sauce Disturbing
With all of my RSpec tests passing, all of my Cucumber scenarios passing, and a bit of defensive Rack middleware, I am ready to deploy my Sinatra / CouchDB application:
jaynestown% rake vlad:stop_app
jaynestown% rake vlad:update vlad:migrate vlad:start_app
Finally, I update DNS so that http://legacy.eeecooks.com points to the legacy Rails site and http://www.eeecooks.com points to the new Sinatra / CouchDB site.

Thus endeth the chain.

Tuesday, October 13, 2009

404 in Sinatra

‹prev | My Chain | next›

Before going live, we need legit 404 and 500 error messages. In production mode, the default Sinatra error messages are a little unhelpful:



Sinatra provides two code blocks for handling errors:
not_found do
end

error do
end
I like having my not found / error templates to be named 404 / 500. Since I am using Haml, I can use the 404.haml and 500.haml templates:
not_found do
haml :'404'
end

error do
haml :'500'
end
I use :'404' because the haml method requires a symbol and :404 is not a valid symbol. After defining the contents of the Haml templates, I have my 404 and 500 error pages.

The only other thing that I do tonight is define the kid nicknames document. We share a lot of personal information about our family in the cookbook, but never the actual kids' names (we're even a little vague about birthdays). Maybe we're paranoid, but...

I have a helper that pulls the nicknames from CouchDB:
    def kid_nicknames
@@kid_kicknames ||= JSON.parse(RestClient.get("#{_db}/kids"))
end
Those nicknames are then used as part of the "wiki" method:
    def wiki(original, convert_textile=true)
text = (original || '').dup
#...
text.gsub!(/\[kid:(\w+)\]/m) { |kid| kid_nicknames[$1] }
#...
end
The seed data for the kids kids document has been empty. I define it:
{
"___":"our daughter",
"___":"our son",
"___":"the baby"
}
And then use my couch_docs gem to load into the CouchDB database:
jaynestown% couch-docs load . http://localhost:5984/eee
With that, I have the nicknames displaying correctly:



That will do for tonight. Tomorrow, I deploy the 404/500 and seed data to beta. Then I can switch beta to be the production site, thus ending my chain.

Sunday, September 27, 2009

A Poor Man's CMS on CouchDB

‹prev | My Chain | next›

Today, I continue my effort to add a poor man's CMS into my Sinatra / CouchDB application. I need to get the catch-all resource to convert the content in a CouchDB document from textile into HTML. An RSpec example describing this:
  context "with an associated CouchDB document" do
before(:each) do
RestClient.
stub!(:get).
and_return('{"content":"*bar*"}')
end

it "should convert textile in the CouchDB doc to HTML" do
get "/foo-bar"
last_response.
should have_selector("strong", :content => "bar")
end
end
To get that to pass, I parse the JSON from CouchDB and use RedCloth to convert the textile in the example into HTML:
get %r{^/([\-\w]+)$} do |doc_id|
begin
data = RestClient.get "#{@@db}/#{doc_id}"
@doc = JSON.parse(data)
rescue RestClient::ResourceNotFound
pass
end
RedCloth.new(@doc['content']).to_html
end
With that working, I would like to insert that HTML into the normal page layout of the site:
    it "should insert the document into the normal site layout" do
get "/foo-bar"
last_response.
should have_selector("title", :content => "EEE Cooks")
end
Getting that to pass is quite easy as Sinatra's haml method is capable of doing just this:
get %r{^/([\-\w]+)$} do |doc_id|
begin
data = RestClient.get "#{@@db}/#{doc_id}"
@doc = JSON.parse(data)
rescue RestClient::ResourceNotFound
pass
end
haml RedCloth.new(@doc['content']).to_html
end
I contemplate adding a feature that will suppress document without a published attribute or add wiki-like intra-document linking ability. Eventually, I come to my senses and listen to the voice whispering YAGNI in my ear. I want a poor-man's CMS, nothing more.

So that should do the trick. To verify that it really is working, I check out the /about-us resource currently in the application:



As expected, it is not found. With my poor-man's CouchDB-based CMS in place, I need to add a CouchDB document with an about-us document ID:



With that, I can then reload the /about-us resource and:



With that mini-feature complete, I will move on to implementing an ingredient index page, which should be quite easy to do with CouchDB map-reduce.

Saturday, September 26, 2009

CouchDB is not a CMS

‹prev | My Chain | next›

On the legacy site, we have several content pages that have yet to make it into the new Sinatra / CouchDB site. The pages include things like an "About this Site" page, an "About Us" page, and pages describing our favorite restaurants.

I could store such pages in the /public directory, but then I would be duplicating headers and footers on each of those pages. As with any duplication, I would have to remember to update the header and footer on each of these static files any time the header/footer Haml partials are updated.

I would like to store these pages in CouchDB, preferably as Textile in a JSON attribute. If the document exists, then the textile would be converted and presented. If the document does not exist, then a 404 would be returned.

To drive this feature, I will describe the fictional resource /foo-bar in an RSpec example:
describe "GET /foo-bar" do
context "without an associated CouchDB document" do
it "should not be found" do
get "/foo-bar"
last_response.status.should == 404
end
end
end
That example passes because Sinatra does not know that resource.

To describe the case when there is a backing CouchDB document, I use this example:
  context "with an associated CouchDB document" do
it "should be found" do
RestClient.stub!(:get).and_return("{}")
get "/foo-bar"
last_response.should be_ok
end
end
end
That example fails because I have no resource to handle it. To get it passing, I need a Sinatra action that responds to something resembling CouchDB resource IDs. Something like this ought to be a good start:
get %r{^/([\-\w]+)$} do |doc_id|
"foo"
end
The textile-couchdb-doc-should-be-found example now passes, but the previous, with-no-corresponding-couchdb-doc example now fails:
1)
'GET /foo-bar without an associated CouchDB document should not be found' FAILED
expected: 404,
got: 200 (using ==)
./spec/eee_spec.rb:605:
The simplest thing that can possibly appease both of these cases is to make a RestClient.get request to the CouchDB resource and, if that fails, to pass handling back to another resource (possibly to be not found anywhere). In other words:
get %r{^/([\-\w]+)$} do |doc_id|
begin
RestClient.get "#{@@db}/#{doc_id}"
rescue RestClient::ResourceNotFound
pass
end
"foo"
end
The pass method comes from Sinatra. It indicates that the currently executing resource does not handle the current request. It passes handling back to Sinatra (in case another resource in the Sinatra application matches) or back to Rack (in case another Rack application is capable of handling this request).

With those two examples passing, I call it a day. I will pick back up tomorrow getting the textile in the document converted to HTML and inserted into the normal Haml layout.

Thursday, September 24, 2009

Full Stack ETag Support

‹prev | My Chain | next›

This is how I have am using Rack::Cache, Sinatra, and CouchDB:
             1. Web client       ^                        
Request | 5. Respond to client
| | and
| | Store in
+---+-------------------+-+ /-----> file system
| | Rack::Cache +-+--- cache
+---+-------------------+-+
| |
+---v-------------------+-+
| |
| Sinatra |
| +----------+
+----+ | |
| +-------------------------+ |
| ^ \
| 2. RestClient | 3. Response |
| Request | _rev: 1234 |
| | |
| +----------------+--------+ \
+--->| | |
| CouchDB |<-----------+
| | 4. Ancillary
| | Requests
+-------------------------+
The nice thing about this stack is that it is all web-based, which will allow me to make certain assumptions when optimizing.

Yesterday, I was able to by-pass step #4 in that diagram which should cut down significantly on the total request time. I used the _rev (revision) attribute returned from CouchDB in step #3 as the argument to Sinatra's etag method. Rack::Cache, in turn, uses that value to decide whether it can use a previously stored cached copy of the HTML generated by Sinatra from the assembled bits of several CouchDB requests.

The action in question:
get '/recipes/:permalink' do
data = RestClient.get "#{@@db}/#{params[:permalink]}"
@recipe = JSON.parse(data)
etag @recipe['_rev']

url = "#{@@db}/_design/recipes/_view/by_date_short"
data = RestClient.get url
@recipes_by_date = JSON.parse(data)['rows']

@url = request.url

haml :recipe
end
If the _rev of the CouchDB recipe document matches the ETag of the HTML document stored in cached, all other processing stops and the cached copy is immediately returned. If they do not match, a new document is generated.

As of yesterday, with the code above, I have that working. What I would like to accomplish today is skipping step #2. In the case that the web browser already has a cached copy of the web page (and hence knows the HTML document's ETag), why bother requesting the entire document from CouchDB? As long as the ETag and CouchDB _rev match, the request life cycle should stay very close to the top of that diagram.

In order to make that happen, I need the RestClient call at the start of the Sinatra action to supply the If-None-Match HTTP request header attribute that corresponds to the ETag response header attribute.

RestClient supports request attributes via optional second argument to the get method. To tell CouchDB to only return a recipe if has been updated, I can use this form:
>> RestClient.get 'http://localhost:5984/eee/2001-09-02-potatoes', :if_none_match =>  "2-2471836896"
=> "{"_id":"2001-09-02-potatoes",
"_rev":"2-2471836896",
"prep_time":10,
"title":"Roasted Potatoes"
...
}
Hmmm... Well, at least I think I should be able to use that form. I am not sure what is going wrong there, but the entire document is being returned. After other troubleshooting fails, I drop down to packet sniffing with tcpdump:
jaynestown% sudo tcpdump -i lo port 5984 -A -s3000
05:48:49.278717 IP localhost.53793 > localhost.5984: P 1:150(149) ack 1 win 513
E...L5@.@............!.`.y.
...............
.[.:.[.:GET /eee/2001-09-02-potatoes HTTP/1.1
If-None-Match: 2-2471836896
Accept: application/xml
Accept-Encoding: gzip, deflate
Host: localhost:5984


05:48:49.278736 IP localhost.5984 > localhost.53793: . ack 150 win 190
E..4;.@.@.. .........`.!.....y.............
.[.:.[.:
05:48:49.282277 IP localhost.5984 > localhost.53793: P 1:221(220) ack 150 win 192
E...;.@.@..,.........`.!.....y.............
.[.;.[.:HTTP/1.1 200 OK
Server: CouchDB/0.9.0a756286 (Erlang OTP/R12B)
Etag: "2-2471836896"
Date: Thu, 24 Sep 2009 09:48:49 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: 1908
Cache-Control: must-revalidate


05:48:49.282309 IP localhost.53793 > localhost.5984: . ack 221 win 530
E..4L6@.@............!.`.y....._.....b.....
.[.;.[.;
05:48:49.282352 IP localhost.5984 > localhost.53793: P 221:2129(1908) ack 150 win 192
E...;.@.@............`.!..._.y.............
.[.;.[.;{"_id":"2001-09-02-potatoes","_rev":"2-2471836896","prep_time":10,"title":"Roasted Potatoes",...
Now c'mon! The request header attribute is being set correctly. It is the same as the ETag and the CouchDB _rev. What am I missing?!

After much head banging, I realize that it is the quotes that I am missing:
>> RestClient.get 'http://localhost:5984/eee/2001-09-02-potatoes', :if_none_match =>  '"2-2471836896"'
RestClient::NotModified: RestClient::NotModified
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient/request.rb:189:in `process_result'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient/request.rb:125:in `transmit'
from /usr/lib/ruby/1.8/net/http.rb:543:in `start'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient/request.rb:123:in `transmit'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient/request.rb:49:in `execute_inner'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient/request.rb:39:in `execute'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient/request.rb:17:in `execute'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.0.3/bin/../lib/restclient.rb:65:in `get'
from (irb):13
from :0
Interesting. I am not sure that this is an exceptional case, but I can certainly catch that exception and signal Rack::Cache to immediately send back its copy.

Just to be sure that I know what is happening I do check the output of tcpdump in this case. Indeed, the quotes are doing the trick:
jaynestown% sudo tcpdump -i lo port 5984 -A -s3000
05:49:10.661038 IP localhost.53802 > localhost.5984: P 1:152(151) ack 1 win 513
E.....@.@..m.........*.`.e....6............
.\...\..GET /eee/2001-09-02-potatoes HTTP/1.1
If-None-Match: "2-2471836896"
Accept: application/xml
Accept-Encoding: gzip, deflate
Host: localhost:5984

05:49:10.663062 IP localhost.5984 > localhost.53802: P 1:156(155) ack 152 win 192
E...5.@.@............`.*..6..e.?...........
.\...\..HTTP/1.1 304 Not Modified
Server: CouchDB/0.9.0a756286 (Erlang OTP/R12B)
Etag: "2-2471836896"
Date: Thu, 24 Sep 2009 09:49:10 GMT
Content-Length: 0
Now that I understand how to make proper RestClient.get calls with a If-None-Match header attribute, I can wrap it in a begin/rescue block in my Sinatra action:
get '/recipes/:permalink' do
data =
begin
RestClient.get "#{@@db}/#{params[:permalink]}",
:if_none_match => request.env["HTTP_IF_NONE_MATCH"]
rescue RestClient::NotModified
etag request.env["HTTP_IF_NONE_MATCH"].gsub(/"/, '')
end


@recipe = JSON.parse(data)
etag @recipe['_rev']

url = "#{@@db}/_design/recipes/_view/by_date_short"
data = RestClient.get url
@recipes_by_date = JSON.parse(data)['rows']

@url = request.url

haml :recipe
end
That behaves as I expected, but what does this all mean? To answer that, I break out Apache Bench to measure response times:
# Access the rack app with Rack::Cache and with full stack etag support:
ab -H "If-None-Match: '2-2471836896'" -n 100 http://localhost:9292/recipes/2001-09-02-potatoes
# Access the rack app with Rack::Cache, but without full stack etag support:
ab -n 100 http://localhost:9292/recipes/2001-09-02-potatoes
# Access the Thin server (no Rack::Cache, no etag support):
ab -n 100 http://localhost:4567/recipes/2001-09-02-potatoes
The results:
StackAverage Req./sec
Full stack etag133.59
Rack::Cache106.01
No etag/no cache10.71
The conclusion that I draw is that I definitely want to use Rack::Cache—100% improvement over reassembling the HTML on each request is too good to pass up. As for the 20% speed boost that full stack ETag buys me, I am not sure that the complexity that is introduced warrants the speed boost. If nothing else, it is worth considering in certain cases.

Wednesday, August 19, 2009

Rack Passenger

‹prev | My Chain | next›

As much fun as HAProxy and thin servers are, I think getting things running under nginx and passenger might be even more fun. So, first up is to install the passenger gem:
sh-3.2$ sudo gem install passenger
I then run through the passenger install wizard:
sh-3.2$ sudo /var/lib/gems/1.8/bin/passenger-install-nginx-module 
Welcome to the Phusion Passenger Nginx module installer, v2.2.4.

This installer will guide you through the entire installation process. It
shouldn't take more than 5 minutes in total.

Here's what you can expect from the installation process:

1. This installer will compile and install Nginx with Passenger support.
2. You'll learn how to configure Passenger in Nginx.
3. You'll learn how to deploy a Ruby on Rails application.

Don't worry if anything goes wrong. This installer will advise you on how to
solve any problems.

Press Enter to continue, or Ctrl-C to abort.
<Enter>

--------------------------------------------

Checking for required software...

* GNU C++ compiler... found at /usr/bin/g++
* Ruby development headers... found
* OpenSSL support for Ruby... found
* RubyGems... found
* Rake... found at /usr/bin/rake
* Zlib development headers... not found

Some required software is not installed.
But don't worry, this installer will tell you how to install them.

Press Enter to continue, or Ctrl-C to abort.
<Enter>

--------------------------------------------

Installation instructions for required software

* To install Zlib development headers:
Please run apt-get install zlib1g-dev as root.

If the aforementioned instructions didn't solve your problem, then please take
a look at the Users Guide:

/var/lib/gems/1.8/gems/passenger-2.2.4/doc/Users guide Nginx.html
Wow, that's nice. It would have taken me a little while to track down the exact library name in the Debian package repository, so I much appreciate the help offered here. Following passenger's instructions, I:
sudo apt-get install zlib1g-dev
Then, after re-running the installer, I get past the required software check and onto:
sh-3.2$ sudo /var/lib/gems/1.8/bin/passenger-install-nginx-module
...
--------------------------------------------

Checking for required software...

* GNU C++ compiler... found at /usr/bin/g++
* Ruby development headers... found
* OpenSSL support for Ruby... found
* RubyGems... found
* Rake... found at /usr/bin/rake
* Zlib development headers... found

--------------------------------------------

Automatically download and install Nginx?

Nginx doesn't support loadable modules such as some other web servers do,
so in order to install Nginx with Passenger support, it must be recompiled.

Do you want this installer to download, compile and install Nginx for you?

1. Yes: download, compile and install Nginx for me. (recommended)
The easiest way to get started. A stock Nginx 0.6.37 with Passenger
support, but with no other additional third party modules, will be
installed for you to a directory of your choice.

2. No: I want to customize my Nginx installation. (for advanced users)
Choose this if you want to compile Nginx with more third party modules
besides Passenger, or if you need to pass additional options to Nginx's
'configure' script. This installer will 1) ask you for the location of
the Nginx source code, 2) run the 'configure' script according to your
instructions, and 3) run 'make install'.

Whichever you choose, if you already have an existing Nginx configuration file,
then it will be preserved.

Enter your choice (1 or 2) or press Ctrl-C to abort: 1<Enter>
I am not much a fan of compiling my web server in addition to the passenger module, but hey, it's my personal site and it is the awesomeness of nginx + passenger. Continuing with the installer:
--------------------------------------------

Where do you want to install Nginx to?

Please specify a prefix directory [/opt/nginx]: <Enter>

Compiling Passenger support files...
...

--------------------------------------------

Nginx with Passenger support was successfully installed.

The Nginx configuration file (/opt/nginx/conf/nginx.conf)
must contain the correct configuration options in order for Phusion Passenger
to function correctly.

This installer has already modified the configuration file for you! The
following configuration snippet was inserted:

http {
...
passenger_root /var/lib/gems/1.8/gems/passenger-2.2.4;
passenger_ruby /usr/bin/ruby1.8;
...
}

After you start Nginx, you are ready to deploy any number of Ruby on Rails
applications on Nginx.

Press ENTER to continue.
<Enter>

--------------------------------------------

Deploying a Ruby on Rails application: an example

Suppose you have a Ruby on Rails application in /somewhere. Add a server block
to your Nginx configuration file, set its root to /somewhere/public, and set
'passenger_enabled on', like this:

server {
listen 80;
server_name www.yourhost.com;
root /somewhere/public; # <--- be sure to point to 'public'!
passenger_enabled on;
}

And that's it! You may also want to check the Users Guide for security and
optimization tips and other useful information:

/var/lib/gems/1.8/gems/passenger-2.2.4/doc/Users guide Nginx.html

Enjoy Phusion Passenger, a product of Phusion (www.phusion.nl) :-)
http://www.modrails.com/

Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.
Those instructions work just as well for a Sinatra application with a rackup file. I currently have my application located in /var/www/eee-code, so my nginx configuration is (mostly from the default configuration from the passenger / nginx install):
worker_processes  2;


events {
worker_connections 1024;
}


http {
passenger_root /var/lib/gems/1.8/gems/passenger-2.2.4;
passenger_ruby /usr/bin/ruby1.8;

include mime.types;
default_type application/octet-stream;

sendfile on;

keepalive_timeout 65;

server {
listen 80;
server_name beta.eeecooks.com;
root /var/www/eee-code/public;
passenger_enabled on;

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
I also have to update the default /etc/init.d/nginx script to point to the proper location for the pid file and the executable daemon:
#! /bin/sh

### BEGIN INIT INFO
# Provides: nginx
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts the nginx web server
# Description: starts nginx using start-stop-daemon
### END INIT INFO

PATH=/opt/nginx/sbin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/opt/nginx/sbin/nginx
#PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
#DAEMON=/usr/sbin/nginx
NAME=nginx
DESC=nginx

test -x $DAEMON || exit 0

# Include nginx defaults if available
if [ -f /etc/default/nginx ] ; then
. /etc/default/nginx
fi

set -e

case "$1" in
start)
echo -n "Starting $DESC: "
start-stop-daemon --start --quiet --pidfile /opt/nginx/logs/$NAME.pid \
--exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --pidfile /opt/nginx/logs/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
;;
restart|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon --stop --quiet --pidfile \
/opt/nginx/logs/$NAME.pid --exec $DAEMON || true
sleep 1
start-stop-daemon --start --quiet --pidfile \
/opt/nginx/logs/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
reload)
echo -n "Reloading $DESC configuration: "
start-stop-daemon --stop --signal HUP --quiet --pidfile /opt/nginx/logs/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
exit 1
;;
esac

exit 0
After stopping my HAProxy frontend to thin servers, I start the nginx server. To make sure that all is well, I check out the HTTP headers via telnet:
cstrom@jaynestown:~/repos/eee-code$ telnet beta.eeecooks.com 80
Trying 97.107.136.191...
Connected to beta.eeecooks.com.
Escape character is '^]'.
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Connection: close
Status: 200
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 2.2.4
Content-Length: 10167
Server: nginx/0.6.37 + Phusion Passenger 2.2.4 (mod_rails/mod_rack)

Connection closed by foreign host.
Nice. I think tomorrow I will start back with code to move the application out of beta. For now, I have gotten my Sinatra / CouchDB application running under nginx passenger, which is a fine place to be.

Saturday, August 1, 2009

So Many Yaks

‹prev | My Chain | next›

I enjoyed a nice break these past few days adding features to couch_design_docs, but it is time to get back to work on the main task at hand. Last I left off with my cookbook application, I had but a few pages to style.

Before I dive back into CSS though, it has been a while since last I ran all of my Cucumber scenarios. Hopefully, they all still run....

They do not. In fact I cannot even run single scenarios:
cstrom@jaynestown:~/repos/eee-code$ cucumber features/recipe_search.feature:53 -b
wrong number of arguments (0 for 1) (ArgumentError)
./features/support/../../eee.rb:24:in `before'
./features/support/../../eee.rb:24
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `polyglot_original_require'
/home/cstrom/.gem/ruby/1.8/gems/polyglot-0.2.5/lib/polyglot.rb:54:in `require'
./features/support/env.rb:5
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `polyglot_original_require'
/home/cstrom/.gem/ruby/1.8/gems/polyglot-0.2.5/lib/polyglot.rb:54:in `require'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:99:in `require_files'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:108:in `each_lib'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:106:in `each'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:106:in `each_lib'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:99:in `require_files'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:53:in `execute!'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/../lib/cucumber/cli/main.rb:26:in `execute'
/home/cstrom/.gem/ruby/1.8/gems/cucumber-0.3.92/bin/cucumber:9
/home/cstrom/.gem/ruby/1.8/bin/cucumber:19:in `load'
/home/cstrom/.gem/ruby/1.8/bin/cucumber:19
Craaap. It has been a while since I last ran my Cucumber scenarios. Did I install a gem that is now conflicting?

I eventually track this down to a conflict between the before filter in my Sinatra application and a method of the same name in Cucumber::StepMother (great name by the way).

I give it a good try—a good long try—but eventually have to concede defeat for the day. Each change I make seems to get me inches closer when I have miles still to go. Maybe I'll use that work or maybe I'll toss it. Most likely the latter, so I stash it away:
cstrom@jaynestown:~/repos/eee-code$ git stash save \
"Trying to solve before filter conflict with Sinatra module namespace"
Saved working directory and index state "On master: Trying to solve before filter conflict with Sinatra module namespace"
HEAD is now at 660ad44 Whoops! Need to use one directory level up now that couch_design_docs handles more than design docs
For now, I resolve the problem the cheap way—with a conditional around the before block in the Sinatra application:
if ENV['RACK_ENV'] != 'test'
before do
content_type 'text/html', :charset => 'UTF-8'
end
end
Eeew. I do not see my first attempt staying in the stash for long. But, it works. I can now run a single scenario:
cstrom@jaynestown:~/repos/eee-code$ cucumber features/recipe_search.feature:53 -b
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Search for recipes

So that I can find one recipe among many
As a web user
I want to be able search recipes

Scenario: Paginating results # features/recipe_search.feature:53
Given 50 yummy recipes # features/step_definitions/recipe_search.rb:119
And a 1 second wait to allow the search index to be updated # features/step_definitions/recipe_search.rb:196
When I search for "yummy" # features/step_definitions/recipe_search.rb:200
Then I should see 20 results # features/step_definitions/recipe_search.rb:243
And I should see 3 pages of results # features/step_definitions/recipe_search.rb:247
And I should not be able to go to a previous page # features/step_definitions/recipe_search.rb:251
When I click page 3 # features/step_definitions/recipe_search.rb:217
Then I should see 10 results # features/step_definitions/recipe_search.rb:243
And I should not be able to go to a next page # features/step_definitions/recipe_search.rb:251
When I click the previous page # features/step_definitions/recipe_search.rb:221
Then I should see 20 results # features/step_definitions/recipe_search.rb:243
And I should be able to go to a previous page # features/step_definitions/recipe_search.rb:256
When I click the next page # features/step_definitions/recipe_search.rb:221
Then I should see 10 results # features/step_definitions/recipe_search.rb:243
When I visit page -1 # features/step_definitions/recipe_search.rb:225
Then I should see page 1 # features/step_definitions/recipe_search.rb:261
When I visit page "foo" # features/step_definitions/recipe_search.rb:225
Then I should see page 1 # features/step_definitions/recipe_search.rb:261
When I visit page 4 # features/step_definitions/recipe_search.rb:225
Then I should see page 1 # features/step_definitions/recipe_search.rb:261

1 scenario (1 passed)
20 steps (20 passed)
0m2.333s
Oh, thank heavens.

After ensuring that my RSpec examples still pass with that conditional, I can finally see if all of my Cucumber scenarios are still passing:
cstrom@jaynestown:~/repos/eee-code$ cucumber features
...

Failing Scenarios:
cucumber features/recipe_search.feature:111 # Scenario: Invalid search parameters
cucumber features/recipe_details.feature:15 # Scenario: Viewing a recipe with non-active prep time
cucumber features/browse_meals.feature:18 # Scenario: Browsing a meal in a given month

32 scenarios (3 failed, 7 undefined, 22 passed)
272 steps (3 failed, 33 skipped, 24 undefined, 212 passed)
Aw, nuts!

If nothing else, my earlier before vs. before yak shaving forced me to update all of my gems. I now have a new version of Cucumber installed that makes things a little easier to resolve. The format of the failing scenarios is such that I can copy & past to run the failing scenario in isolation:
cstrom@jaynestown:~/repos/eee-code$ cucumber features/recipe_search.feature:111
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Search for recipes

So that I can find one recipe among many
As a web user
I want to be able search recipes

Scenario: Invalid search parameters # features/recipe_search.feature:111
Given 5 "Yummy" recipes # features/step_definitions/recipe_search.rb:119
And a 0.5 second wait to allow the search index to be updated # features/step_definitions/recipe_search.rb:196
When I search for "" # features/step_definitions/recipe_search.rb:200
Then I should see no results # features/step_definitions/recipe_search.rb:316
And I should see an empty query string # features/step_definitions/recipe_search.rb:324
expected following output to contain a <input[@name=query][@value='']/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>EEE Cooks</title>
<link href="/stylesheets/style.css" rel="stylesheet" type="text/css">
</head>
<html><body>
<div id="header">
<div id="eee-header-logo">
<a href="/">
<img alt="Home" src="/images/eee_corner.png"></a>
</div>
</div>
<ul id="eee-categories">
<li><a href="/recipes/search?q=category:italian">Italian</a></li>
<li><a href="/recipes/search?q=category:asian">Asian</a></li>
<li><a href="/recipes/search?q=category:latin">Latin</a></li>
<li><a href="/recipes/search?q=category:breakfast">Breakfast</a></li>
<li><a href="/recipes/search?q=category:chicken">Chicken</a></li>
<li><a href="/recipes/search?q=category:fish">Fish</a></li>
<li><a href="/recipes/search?q=category:meat">Meat</a></li>
<li><a href="/recipes/search?q=category:salad">Salad</a></li>
<li><a href="/recipes/search?q=category:vegetarian">Vegetarian</a></li>
<a>Recipes</a>
</ul>
<form action="/recipes/search" method="get">
<input maxlength="2048" name="q" size="31" type="text" value=""><input name="s" type="submit" value="Search">
</form>
<p class="no-results">
No results matched your search. Please refine your search
</p>
<div id="footer"></div>
</body></html>
</html>
(Spec::Expectations::ExpectationNotMetError)
features/recipe_search.feature:117:in `And I should see an empty query string'
When I search for an invalid lucene search term like "title:ingredient:egg" # features/step_definitions/recipe_search.rb:213
Then I should see no results # features/step_definitions/recipe_search.rb:316
And I should see an empty query string # features/step_definitions/recipe_search.rb:324

Failing Scenarios:
cucumber features/recipe_search.feature:111 # Scenario: Invalid search parameters

1 scenario (1 failed)
8 steps (1 failed, 3 skipped, 4 passed)
Ah, the query parameter should be "q", not "query". That is an easy enough fix:
Then /^I should see an empty query string$/ do
response.should have_selector("input[@name=q][@value='']")
end
The next failing Cucumber scenario is similarly easy to get passing. Some added tags require some RegExps where a string had sufficed before. The last failing scenario uncovers an actual bug:
cstrom@jaynestown:~/repos/eee-code$ cucumber features/browse_meals.feature:18
Sinatra::Test is deprecated; use Rack::Test instead.
Feature: Browse Meals

So that I can find meals made on special occasions
As a person interested in exploring meals and how they drive certain recipes
I want to browse meals by date

Scenario: Browsing a meal in a given month # features/browse_meals.feature:18
Given a "Even Fried, They Won't Eat It" meal enjoyed in May 2009 # features/step_definitions/meal_details.rb:1
And a "Salad. Mmmm." meal enjoyed in April 2009 # features/step_definitions/meal_details.rb:1
And a "Almost French Onion Soup" meal enjoyed in September 2003 # features/step_definitions/meal_details.rb:1
When I view the list of meals prepared in May of 2009 # features/step_definitions/meal_details.rb:47
Then I should see the "Even Fried, They Won't Eat It" meal among the meals of this month # features/step_definitions/meal_details.rb:81
And I should not see the "Salad. Mmmm." meal among the meals of this month # features/step_definitions/meal_details.rb:85
And I should not see a link to June 2009 # features/step_definitions/meal_details.rb:97
When I follow the link to the list of meals in April 2009 # features/step_definitions/meal_details.rb:57
Could not find link with text or title or id "April 2009" (Webrat::NotFoundError)
features/browse_meals.feature:27:in `When I follow the link to the list of meals in April 2009'
Then I should not see the "Even Fried, They Won't Eat It" meal among the meals of this month # features/step_definitions/meal_details.rb:85
And I should see the "Salad. Mmmm." meal among the meals of this month # features/step_definitions/meal_details.rb:81
And I should see a link to May 2009 # features/step_definitions/meal_details.rb:93
And I should not see a link to February 2009 # features/step_definitions/meal_details.rb:97
When I follow the link to the list of meals in September 2003 # features/step_definitions/meal_details.rb:57
Then I should see the "Almost French Onion Soup" meal among the meals of this month # features/step_definitions/meal_details.rb:81
And I should see a link to April 2009 # features/step_definitions/meal_details.rb:93

Failing Scenarios:
cucumber features/browse_meals.feature:18 # Scenario: Browsing a meal in a given month

1 scenario (1 failed)
15 steps (1 failed, 7 skipped, 7 passed)
Looking at the actual meals-by-month web page (it's nice to be able to do that now), I see that the intra-month links are not actual links and have the wrong date:



That turns out to be another yak. I have had my fill of yaks for the day, so I will start with that one tomorrow.

Friday, July 24, 2009

A Mediocre Solution for Finding Adjacent CouchDB View Records

‹prev | My Chain | next›

I have one remaining open issue in my GitHub tracker: links between recipes are missing. I made a go at fixing the problem last night, but had to back out when the fix was growing too large.

Part of the problem is that the helper method responsible for linking to the next record in a CouchDB view has grown long and complicated:
    def link_to_adjacent_view_date(current, couch_view, options={})
# If looking for the record previous to this one, then we seek a
# date prior to the current one - build a Proc capable of
# finding that
compare = options[:previous] ?
Proc.new { |date_fragment, current| date_fragment < current} :
Proc.new { |date_fragment, current| date_fragment > current}

# If looking for the record previous to this one, then we need
# to reverse the list before using the compare Proc to detect
# the record
next_result = couch_view.
send(options[:previous] ? :reverse : :map).
detect{|result| compare[result['key'], current.to_s]}

# If a next record was found, then return link text
if next_result
next_uri = next_result['id'].gsub(/-/, '/')
link_text = block_given? ?
yield(next_result['id'], next_result['value']) :
next_result['id']

%Q|<a href="/meals/#{next_uri}">#{link_text}</a>|
else
""
end
end
The most obvious obstacle in adapting this helper for use with recipes is the line that produces the <a> tag—the "/meals" URI-space is hard coded in there. But how to drive the URI-space in that method?

The quickest means of accomplishing this is to add a urispace argument to the link_to_adjacent_view_date helper. That is not an acceptable option in my mind because link_to_adjacent_view_date already has an explicit arity of 3. I barely remember what the three arguments do—adding a fourth is going to make it impossible. Hiding it in the options hash argument is disingenuous, at best.

I called it an explicit arity of 3 earlier because this helper takes a fourth block argument. It is the responsibility of the block to build the link text. Given that the actual arity is 4, adding yet another argument is right out. But I ought to be able to increase the responsibility of the block—instead of building the link text, it can build the entire link.

In other words, given a CouchDB view with results from April and May of 2009:
    before(:each) do
@by_month = [{"key" => "2009-04", "value" => "foo"},
{"key" => "2009-05", "value" => "bar"}]
end
Then, when working with the record adjacent to April 2009, I should be able to build a link to the value from May, "bar" in this case:
    it "should link to the CouchDB view's key and value, if block is given" do
link_to_adjacent_view_date("2009-04", @by_month) do |rec|
%Q|<a href="/foo">#{rec}</a>|
end.
should have_selector("a",
:href => "/foo",
:content => "bar")
end
I can make that pass with a somewhat simpler output conditional:
      # If a next record was found, then return link text
if next_result
if block_given?
yield next_result['value']
else
next_uri = next_result['key'].gsub(/-/, '/')
%Q|<a href="/meals/#{next_uri}">#{next_result['key']}</a>|
end
else
""
end
If a block if given, the result of the conditional is the entire block itself. If no block is given, then a default, meal-centric (for backward compatibility) string results.

The specs all pass for the helper. As expected, the specs for the meal view fail (since it is not longer generating a link to the text. After correcting that, I drive intra-recipe links. The specs are largely based on the intra-meal links, making the process relatively easy. And, like that, intra-recipe links are working:



I close the issue with that fix, but I am not happy with the ultimate solution. I think that Rails concepts and habits have had a bad influence on me in this case. Specifically, I am treating helpers like Rails's view helpers and RestClient calls to CouchDB as model interactions. Neither is the case. In simple Sinatra apps, helpers can help views or controllers and RestClient is pulling back Hash objects, not MVC models.

Ultimately, I think a cleaner solution would have been to have the link_to_adjacent_view_date helper request the appropriate CouchDB view directly, using limit=1 to pull back the single next record. Since I have this working, I leave that to another day with a TODO note.

Wednesday, July 22, 2009

Annoyances

‹prev | My Chain | next›

Exploring through the site a bit, I notice that I need to default the output to UTF-8. All the data is stored in UTF-8. Things like em-dashes look OK when viewed directly in CouchDB:



But not so OK in Sinatra:



To set the default character encoding in Sinatra, use a before filter:
before do
content_type 'text/html', :charset => 'UTF-8'
end
With that, I have my em-dashes displaying OK:



I could have accomplished just as easily by adding a meta tag to the Haml template. It comes down to a personal preference for me. I rationalize it by thinking of data as a systemic consideration, not a presentation thing.

Next up, I take some to work through some of the issues that I am tracking. While fixing the search page, I notice that I am unable to search on multiple terms (e.g. "fish sticks"). This was caused by not URL encoding the search term when passing it off to couchdb-lucene. The example that I need to pass:
    it "should be able to search multiple terms" do
RestClient.should_receive(:get).
with(/q=foo\+bar/).
and_return('{"total_rows":30,"skip":0,"limit":20,"rows":[]}')

get "/recipes/search?q=foo+bar"
end
The code that makes this pass (using Rack::Utils.escape):
get '/recipes/search' do
@query = params[:q]

page = params[:page].to_i
skip = (page < 2) ? 0 : ((page - 1) * 20)

couchdb_url = "#{@@db}/_fti?limit=20" +
"&q=#{Rack::Utils.escape(@query)}" +
"&skip=#{skip}"

...
(commit)

I have two more minor issues in the tracker that need fixing, but everything else is looking good. After addressing those issues, it will finally be time to explore less to resolve my lack of CSS.

Tuesday, July 14, 2009

Over 1,000 Documents

‹prev | My Chain | next›

With the couch_design_docs gem, I am able to easily drop and recreate my development (and ultimately my production) CouchDB database. This all began because I wanted to load all of my meals and recipes in to my development database. So let's do it!

First up, I drop my old database:



Then recreate it:



Now I reload all of my design documents with couch_design_docs and the rake task that I created yesterday:
require 'couch_design_docs'
task :load_design_docs do
CouchDesignDocs.upload_dir("http://localhost:5984/eee", "couch/_design")
end
After running rake load_design_docs, I do a quick double check to find that yes, my design documents are now in the database:



Now that I think about it, I will likely be dropping and recreating my development CouchDB quite a bit now that the couch_design_docs gem makes it easy to reload my design docs. Rather than going through that manual process each time, I ought to automate this with rake (and do a little namespace organization while I am at it):
namespace :couchdb do

desc "Drop and re-create the CouchDB database, loading the design documents after creation"
task :reset => [:drop, :create, :load_design_docs]

desc "Create a new version of the CouchDB database"
task :create do
RestClient.put DB, { }
end

desc "Delete the current the CouchDB database"
task :drop do
RestClient.delete DB
end

require 'couch_design_docs'

desc "Load (replacing any existing) all design documents"
task :load_design_docs do
CouchDesignDocs.upload_dir(DB, "couch/_design")
end
end
It has been a while since I uploaded documents from my legacy Rails application into my new CouchDB store. The instructions for uploading my recipes include re-opening the Recipe class to add methods for CouchDB JSON generation:
class Recipe < ActiveRecord::Base

def _id; date.to_s + '-' + self.label end

def tag_names; tags.map(&:name) end

def _attachments
if self.image && self.image.filename
{
self.image.filename =>
{
:data => Base64.encode64(File.open(self.image.full_filename).read).gsub(/\n/, ''),
:content_type => "image/jpeg"
}
}
end
end

def couch_json
def self.type; "Recipe" end

self.to_json( :methods => [:tag_names, :_id, :_attachments],
:include => {
:preparations =>
{
:include =>
{
:ingredient => { :except => :id }
},
:except => [:ingredient_id, :recipe_id, :id]
},
:tools => { :except => [:id, :label] } },
:except => [:id, :label]).sub(/\{/, '{"type":"Recipe",')
end
end
I then run through each recipe in my legacy rails database, using the couch_json method to upload these documents to CouchDB:
>> ActiveSupport.use_standard_json_time_format=true
>> require 'restclient'
>> Recipe #load the current recipe class so that I re-open, not define
>> class Recipe < ActiveRecord::Base ... # the rest of the re-opened class from above
>> Recipe.all.each {|r| RestClient.put "http://localhost:5984/eee/#{r._id}", r.couch_json, :content_type => 'application/json'}
Similarly, the instructions for uploading my meals also have me re-open the Meal class to add methods for CouchDB JSON:
class Meal < ActiveRecord::Base
# IDs - date suffices for a meal (we never do more than one meal per day)
def _id; date.to_s end

# JSON for the CouchDB Document
def couch_json
self.to_json(:methods => [:_id, :menu, :type, :_attachments], :except => [:id, :image_old])
end

# For uploading meal images
def _attachments
if self.image && self.image.filename
{
self.image.filename =>
{
:data => Base64.encode64(File.open(self.image.full_filename).read).gsub(/\n/, ''),
:content_type => "image/jpeg"
}
}
end
end

# For the menu
def menu; menu_items.map(&:name) end

# To distinguish between meals, recipes, etc.
def type; self.class.to_s end
end
And, in Irb:
>> Meal.all.each{|m| RestClient.put "http://localhost:5984/eee/#{m._id}", m.couch_json, :content_type => 'application/json'}
With data in the application, it is time to fire up Sinatra. Initially, I get an error about missing the "kids" document in CouchDB (used to lookup nicknames that we use for the kids). After creating an empty kids document, I am able to navigate to http://localhost:4567 to see:



Yay! Over 1,000 documents (recipes and meals) are now loaded in my app and it seems to be working. I will do some smoke testing tomorrow to make sure that all is well. Then I need to figure out how to handle seed data like that "kids" document.

Update: The instructions were updated to reflect the need to format the dates in ISO 8601 format by setting ActiveSupport.use_standard_json_time_format=true.

Sunday, June 7, 2009

Rack Test with RSpec

‹prev | My Chain | next›

No too long ago, I upgraded to Sinatra 0.9.2. Ever since then I've been getting deprecation warnings in my RSpec output:
cstrom@jaynestown:~/repos/eee-code$ rake
(in /home/cstrom/repos/eee-code)

==
Sinatra app spec
Sinatra::Test is deprecated; use Rack::Test instead.
.......................
Since I've been mucking about with Rack recently, now is a good time to address that deprecation warning.

First up, I gem install rack-test. Next I update my spec_helper.rb by replacing:
require 'sinatra/test'
with:
require 'rack/test'
Also, per the Sinatra testing documentation, I inject Rack test methods into Test::Unit::TestCase:
Test::Unit::TestCase.send :include, Rack::Test::Methods
Finally (also per the documentation), I add an app method so that Rack::Test has somewhere to send requests:
def app
Sinatra::Application
end
After all that, when I run my specs, I get:
cstrom@jaynestown:~/repos/eee-code$ rake
(in /home/cstrom/repos/eee-code)

==
Sinatra app spec
F..F..F.FFF........FFFF

1)
NoMethodError in 'eee a CouchDB meal GET /meals/YYYY should respond OK'
undefined method `ok?' for nil:NilClass
./spec/eee_spec.rb:46:

2)
NoMethodError in 'eee a CouchDB meal GET /meals/YYYY/MM should respond OK'
undefined method `ok?' for nil:NilClass
./spec/eee_spec.rb:72:

3)
NoMethodError in 'eee a CouchDB meal GET /meals/YYYY/MM/DD should respond OK'
undefined method `ok?' for nil:NilClass
./spec/eee_spec.rb:104:

4)
NoMethodError in 'eee a CouchDB recipe GET /recipes/permalink should respond OK'
undefined method `ok?' for nil:NilClass
./spec/eee_spec.rb:141:

5)
'eee a CouchDB recipe GET /recipes/:permalink/:image should retrieve the image' FAILED
expected Rack::Lint::LintError but nothing was raised
./spec/eee_spec.rb:155:

6)
NoMethodError in 'eee a CouchDB recipe GET /recipes/:permalink/:image should return 404 for a non-existent image'
undefined method `not_found?' for nil:NilClass
./spec/eee_spec.rb:161:

7)
'eee GET /recipes/search should display a helpful message when no results' FAILED
expected the following element's content to include "No results":
./spec/eee_spec.rb:244:

8)
NoMethodError in 'eee GET /recipes/search should redirect without pagination after navigating beyond the pagination window'
undefined method `status' for nil:NilClass
./spec/eee_spec.rb:253:

9)
'eee GET /recipes/search should treat couchdb errors as no-results' FAILED
expected the following element's content to include "No results":
./spec/eee_spec.rb:263:

10)
'eee GET /recipes/search should treat couchdb-lucene errors as an empty query' FAILED
expected following output to contain a <input[@name=query][@value='']/> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

./spec/eee_spec.rb:272:

Finished in 0.315517 seconds

23 examples, 10 failures
I think most of those failures are likely due to using the old response from sinatra/test instead of the last_response from rack/test. Searching/replacing in my spec finds 10 occurrences, so maybe everything is working now:
 cstrom@jaynestown:~/repos/eee-code$ rake
(in /home/cstrom/repos/eee-code)

==
Sinatra app spec
.........F.............

1)
'eee a CouchDB recipe GET /recipes/:permalink/:image should retrieve the image' FAILED
expected Rack::Lint::LintError but nothing was raised
./spec/eee_spec.rb:155:

Finished in 0.293289 seconds

23 examples, 1 failure
Hmm... After some investigating, I find that spec to be an odd one:
    describe 'GET /recipes/:permalink/:image' do
it "should retrieve the image" do
data = RestClient.get "#{@@db}/#{@permalink}"
recipe = JSON.parse(data)

RestClient.put "#{@@db}/#{@permalink}/sample.jpg?rev=#{recipe['_rev']}",
File.read('spec/fixtures/sample.jpg'),
:content_type => 'image/jpeg'


lambda { get "/images/#{@permalink}/sample.jpg" }.
should raise_error(Rack::Lint::LintError)
end
What on Earth was I thinking when I wrote that? Normally I would be kicking myself for not leaving a comment behind on something like. Thankfully, I have plenty of documentation in my chain. This particular spec was written because I could not satisfactorily simulate a Sinatra session—my ultimate (unsatisfactory) solution was to test the spec library's implementation. With Rack::Test, I no longer need to do that, so I replace the lambda/should-raise_error weirdness with a simple get and should-be_ok:
    describe 'GET /recipes/:permalink/:image' do
it "should retrieve the image" do
data = RestClient.get "#{@@db}/#{@permalink}"
recipe = JSON.parse(data)

RestClient.put "#{@@db}/#{@permalink}/sample.jpg?rev=#{recipe['_rev']}",
File.read('spec/fixtures/sample.jpg'),
:content_type => 'image/jpeg'

get "/images/#{@permalink}/sample.jpg"
last_response.should be_ok

end
And now...
cstrom@jaynestown:~/repos/eee-code$ rake
(in /home/cstrom/repos/eee-code)

==
Sinatra app spec
.......................

Finished in 0.396667 seconds

23 examples, 0 failures

==
Helper specs
..............................................

Finished in 0.039739 seconds

46 examples, 0 failures

==
View specs
...................................................

Finished in 0.319114 seconds

51 examples, 0 failures
Yay! All my specs are passing and I was even able to get rid of a poor spec, making this excursion very much worthwhile.
(commit)

Wednesday, June 3, 2009

Rackup

‹prev | My Chain | next›

With 150 of 200 Cucumber steps defined and passing, it is time to start thinking about deployment. It doesn't hurt that I need to do some research for an upcoming presentation.

Ultimately, I think that I will end up deploying to a Thin or Passenger server, which will hand off most requests to my little Sinatra app. To do either, I can use Rack.

Sinatra already uses Rack for much of its innards. Still it can't hurt to make sure that I can run with Rack. As with any Rack application, I create a config.ru file. This file is especially sparse for Sinatra due to the already tight integration of the two. All I need to do is require my app and run it:
require 'eee'
run Sinatra::Application
I can verify my minimalistic Rack configuration with the rackup command (no arguments) and navigating to the meals in 2006 URL on port 9292 (the default for rackup). I have a single meal from 2006 in my CouchDB database, which I see on that page:



Nice! Everything looks to be in order. I do not have much data in my development DB, so I will not be able to smoke test much. Maybe just a link or two. The navigation between years seems to work—I can click on the the year 2003 and see "Almost French Onion Soup" listed as a meal that we prepared that year. But when I click that meal, I get this error:



uninitialized class variable @@db in Eee::Helpers? Sounds like fun.

To aid in isolation testing, I define all of my helpers in a module with a namespace of Eee::Helpers. I then mix those helpers into the Sinatra app's helper via the helpers block:
helpers do
include Eee::Helpers
end
Those method ought to have access to the Sinatra class variables, which are defined via Sinatra configure blocks:
configure :development, :production do
@@db = "http://localhost:5984/eee"
end
The helpers ought to have access to class variables (at least in my understanding), but clearly they do not.

OK, so let's ask the current object what class variables are available. In the topmost method of the call stack, I raise the answer to that question:
    def _db
raise self.class.class_variables.join(", ")
end
After restarting Rack, I get my answer:



@@db is a class variable in the current scope. So what gives? Best I can figure (and I can only guess at this point) is that either the helpers or the configures define things on the eigenclass of the Sinatra app, while the other is on the class proper. I may have to stick with my guess because the Sinatra code includes some heavy meta-programming including sub-classing self (class << self) and class_eval. I think I'll risk programming by coincidence and guess there's an eigenclass involved somewhere in there.

If that is the case, then I ought to be able to ask the class for the value of the @@db class variable and be done with it:
    def _db
self.class.send(:class_variable_get, "@@db")
end
Indeed that does work.

It's been an interesting night looking through Sinatra code. Interesting but not much progress with Rack other than getting it running. Tomorrow I will make sure that I can run with both Thin and Passenger and then explore some Rack middleware.

Wednesday, May 13, 2009

Browsing Meals

‹prev | My Chain | next›

Up next, according to Cucumber (my master), is the "Browse Meals" feature. The first scenario in there is "Browsing a meal in a given year":
  Scenario: Browsing a meal in a given year
Given a "Even Fried, They Won't Eat It" meal enjoyed in 2009
When I view the list of meals prepared in 2009
Then "Even Fried, They Won't Eat It" should be included in the list

Given a "Even Fried, They Won't Eat It" meal enjoyed in 2009
And a "Salad. Mmmm." meal enjoyed in 2008
When I view the list of meals prepared in 2009
Then I should be able to follow a link to the list of meals in 2008
And "Salad. Mmmm." should be included in the list
This was one of the first scenarios that I wrote and it shows, I think. I have the same "Given" and the order of the steps reads a bit off. Re-organizing the scenario a bit:
  Scenario: Browsing a meal in a given year

Given a "Even Fried, They Won't Eat It" meal enjoyed in 2009
And a "Salad. Mmmm." meal enjoyed in 2008
When I view the list of meals prepared in 2009
Then the "Even Fried, They Won't Eat It" meal should be included in the list
And the "Salad. Mmmm." meal should not be included in the list
When I follow the link to the list of meals in 2008
Then the "Even Fried, They Won't Eat It" meal should not be included in the list
And the "Salad. Mmmm." meal should be included in the list
Much better.

My "Givens" are declared at the outset. There are two paths being followed (one for 2009, one for 2008), both starting with "When" declarations. Best of all, the second "When" flows from the first—clicking a link displayed in the first.

Implementing the first two steps can be accomplished via a single Given block:
Given /^a "([^\"]*)" meal enjoyed in (\d+)$/ do |title, year|
date = Date.new(year.to_i, 5, 13)

permalink = "id-#{date.to_s}"

meal = {
:title => title,
:date => date,
:serves => 4,
:summary => "meal summary",
:description => "meal description"
}

RestClient.put "#{@@db}/#{permalink}",
meal.to_json,
:content_type => 'application/json'
end
The next step, viewing the list of meals in 2009, can be defined as:
When /^I view the list of meals prepared in 2009$/ do
visit("/meals/2009")
response.status.should == 200
end
It fails, of course, since I have to define the meals action, so into the code I go...

As with recipes, I write my meal creation / tear down before / after blocks (this ain't no relational DB with fancy transactions):
  context "a CouchDB meal" do
before(:each) do
@date = Date.new(2009, 5, 13)
@title = "Meal Title"
@permalink = "id-#{@date.to_s}"

meal = {
:title => @title,
:date => @date,
:serves => 4,
:summary => "meal summary",
:description => "meal description"
}

RestClient.put "#{@@db}/#{@permalink}",
meal.to_json,
:content_type => 'application/json'

end

after(:each) do
data = RestClient.get "#{@@db}/#{@permalink}"
meal = JSON.parse(data)

RestClient.delete "#{@@db}/#{@permalink}?rev=#{meal['_rev']}"
end
end
The first meals action example is a simple one:
    describe "GET /meals/YYYY" do
it "should respond OK" do
get "/meals/2009"
response.should be_ok
end
end
This fails, of course since the action has not been defined. Let's define it and call it a night:
get %r{/meals/(\d+)} do |year|
end
(commit)
(commit)

Three steps down, 5 to go in the first meal scenario:



Looks like some fun with map-reduce is in store for tomorrow!

Thursday, May 7, 2009

Fixing a Mistake That Should Have Been Caught By a Spec

‹prev | My Chain | next›

By completing the implementation of the recipe search scenarios, I inadvertently broke an earlier scenario:
cstrom@jaynestown:~/repos/eee-code$ cucumber -n features -s "Paginating results"
Feature: Search for recipes

So that I can find one recipe among many
As a web user
I want to be able search recipes

Scenario: Paginating results
Given 50 yummy recipes
And a 0.5 second wait to allow the search index to be updated
When I search for "yummy"
Then I should see 20 results
And I should see 3 pages of results
And I should not be able to go to a previous page
When I click page 3
Then I should see 10 results
And I should not be able to go to a next page
When I click the previous page
Then I should see 20 results
And I should be able to go to a previous page
When I click the next page
Then I should see 10 results
When I visit page -1
Then I should see page 1
When I visit page "foo"
Then I should see page 1
When I visit page 4
Then I should see page 1
expected following output to contain a <.pagination span.current>1</.pagination span.current> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<table><tr>
<th>
<a href="/recipes/search?q=yummy&sort=sort_title" id="sort-by-name">Name</a>
</th>
<th>
<a href="/recipes/search?q=yummy&sort=sort_date&order=desc" id="sort-by-date">Date</a>
</th>
<th>
<a href="/recipes/search?q=yummy&sort=sort_prep" id="sort-by-prep">Prep</a>
</th>
<th>
<a href="/recipes/search?q=yummy&sort=sort_ingredient" id="sort-by-ingredients">Ingredients</a>
</th>
</tr></table>
<div class="pagination">
<a href="/recipes/search?q=yummy&page=3">« Previous</a><a href="/recipes/search?q=yummy&page=1">1</a><a href="/recipes/search?q=yummy&page=2">2</a><a href="/recipes/search?q=yummy&page=3">3</a><a href="/recipes/search?q=yummy&page=5">Next »</a>
</div>
</body></html>
(Spec::Expectations::ExpectationNotMetError)
features/recipe_search.feature:73:in `Then I should see page 1'

1 scenario
1 failed step
19 passed steps
I am expecting that when the user navigates beyond the pagination window (e.g. through a URL hack), the application will redirect the user to the first page of the search. That is not happening—the user is seeing an empty page 5 instead.

Looking at the code, the redirect occurs if the total rows are zero:
  if @results['total_rows'] == 0 && page > 1
redirect("/recipes/search?q=#{@query}")
return
end
That is where I made my mistake. I do not want to redirect when there are no results. I want to redirect when there are results, but none on the current page.

I am a little annoyed with myself that I never made an example describing this behavior. I did drive the behavior with an example, but glossed over the redirect, only testing the behavior after the redirect.

I can rectify that, but the test is a little ugly:
    it "should redirect without pagination after navigating beyond the pagination window" do
RestClient.stub!(:get).
and_return('{"total_rows":1,"skip":0,"limit":20,"rows":[]}')

get "/recipes/search?q=egg&page=2"

response.status.should == 302
response.headers["Location"].should == "/recipes/search?q=egg"
end
The ugliness comes from testing the redirect. If I were doing this with Rails, I could specify that the response.should redirect_to(...), but this is the best I could come up with a Sinatra app.

With code to implement that example in place, I have better coverage and I have all of my tests and scenarios passing. Most of the time.

More on that tomorrow.

(commit)

Tuesday, April 28, 2009

Sorting

‹prev | My Chain | next›

Up first in the sorting scenario are the creation of sortable, dummy recipes:
Given /^(\d+) "([^\"]*)" recipes with ascending names, dates, preparation times, and number of ingredients$/ do |count, keyword|
date = Date.new(2008, 4, 28)

(1..count.to_i).each do |i|
permalink = "id-#{i}-#{keyword.gsub(/\W/, '-')}"

recipe = {
:title => "#{keyword} recipe #{i}",
:date => date + i,
:prep_time => i,
:preparations =>
(1..count.to_i).
map {|j| { :ingredient => { :name => "ingredient #{j}"}} }
}

RestClient.put "#{@@db}/#{permalink}",
recipe.to_json,
:content_type => 'application/json'
end
end
There are a few differences between this and the creation of the dummy records for pagination. The date for each recipe exploits date arithmetic by adding a day to each subsequent recipe. Similarly, each recipe has 1 more ingredient that its predecessor.

With that, there are 4 steps passing (3 were defined by other scenarios) and 6 skipped (also defined by other scenarios, but not reached). This leave 13 that need to be defined.



Before wading into the code, I think I will implement the next undefined step (clicking the search results header for sorting). Doing so will get my mind right for implementing examples:
When /^I click the "([^\"]*)" column header$/ do |link|
click_link("sort-by-#{link.downcase()}")
end
When clicking the "Name" column heading, for example, I expect to find it in an a tag with an id of "sort-by-name".

Unfortunately, when I start work on the view, I run into a problem implementing this example:
  it "should link to sort by date" do
assigns[:query] = "foo"
render("/views/search.haml")
response.should have_selector("th > a",
:href => "/recipes/search?q=foo&sort=name",
:content => "name")
end
The error that occurs is:
cstrom@jaynestown:~/repos/eee-code$ spec ./spec/views/search.haml_spec.rb
.....F

1)
'search.haml should link to sort by date' FAILED
expected following output to contain a <th > a href='/recipes/search?q=foo&sort=name'>name</th > a> tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<table>
<tr>
<th>
<a href="/recipes/search?q=foo&sort=name">Name</a>
</th>
...
Initially, I think the problem is that Haml is escaping the ampersand that is separating the query parameters. I am not expecting it to do so.

I spent a lot of time Googling to see how to prevent Haml from escaping the href attribute. Ultimately I was unsuccessful in that pursuit. What I did find was that it is apparently OK to escape them in query parameters. I knew about the semi-colon separators from my XML/XSL days, but being able to use &amp; is news to me. Something for #standup tomorrow!

Ultimately, this was not the problem. My mistake was that I was expecting lowercase "name" in the a tag, but am generating an upper case "Name". Once fixed, all specs pass for tonight.

Really could have used a pair to save me from wasting time tonight. Ah well, there's always tomorrow.
(commit)