Friday, August 7, 2009

Ramaze, Sequel, and Search (Round 2)

After my last post, Jeremy Evans had a suggestion that I felt was worth passing on. He points out that you probably shouldn't be using datasets in models and views and instead should move them to the models and let the model handle it. So ... here's the new controller controllers/main_controller.rb

# controllers/main_controller.rb
#
# The mainController has a two methods index and search_results. First map to /
# for the view. Next, set the layout to page so that we use the
# layout/page.xhtml for our layout.
class MainController < Ramaze::Controller

# The Admin controller will be accessed using "admin" as in:
# http://localhost:7000/admin.
map '/'

# Use page.xhtml in the layout directory for layout
layout :page

# You can access it now with http://localhost:7000/
def index
@title = "Search Example"
end

# Calculate and display the search results.
def search_results
@title = "Search Example - Results"

# Grab the search_string from the request hash. This is generated when the user inputs
# something into the Search box in the view/index.xhtml file.
@search_string = request[:search]
@search_response = Book.search(@search_string.split)
end
end



and the new models/models.rb

#
# This is the model for the book and is backed by the :book table in the
# database.
#
# Create the Book model.
class Book < Sequel::Model
def self.search(terms)
Book.grep([:title, :description], terms.map{|x| "%#{x} %"}).all
end
end


Not too big a change, but it does make things a bit easier to use and test.

As always, let me know if you have questions.

No comments:

Post a Comment