Database Reference
In-Depth Information
3.3.3
Viewing the archive
You'll use Ruby's Sinatra web framework to build a simple app to display the results.
Create a file called viewer.rb and place it in the same directory as the other scripts.
Next, make a subdirectory called views , and place a file there called tweets.erb. The
project's file structure should looks like this:
- config.rb
- archiver.rb
- update.rb
- viewer.rb
- /views
- tweets.erb
Now edit viewer.rb with the following code.
Listing 3.2
A simple Sinatra application for displaying and searching the Tweet archive
require 'rubygems'
require 'mongo'
require 'sinatra'
B
Require
libraries
require 'config'
C
Instantiate
collection
for tweets
configure do
db = Mongo::Connection.new[DATABASE_NAME]
TWEETS = db[COLLECTION_NAME]
end
get '/' do
if params['tag']
selector = {:tags => params['tag']}
else
selector = {}
end
D
Dynamically build
query selector
E
Or use
blank selector
F
Issue query
@tweets = TWEETS.find(selector).sort(["id", -1])
G
Render view
erb :tweets
end
The first lines require the necessary libraries along with your config file B . Next
there's a configuration block that creates a connection to MongoDB and stores a ref-
erence to your tweets collection in the constant TWEETS C .
The real meat of the application is in the lines beginning with get '/' do . The
code in this block handles requests to the application's root URL . First, you build your
query selector. If a tags URL parameter has been provided then you create a query
selector that restricts the result set to the given tags D . Otherwise, you create a blank
selector, which returns all documents in the collection E . You then issue the query F .
By now you should know that what gets assigned to the @tweets variable isn't a result
set, but a cursor. You'll iterate over that cursor in your view.
The last line G renders the view file tweets.erb, whose full code listing is shown next.
 
Search WWH ::




Custom Search