Created
January 21, 2010 08:30
-
-
Save collin/282673 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module DataMapper | |
module Search | |
module SearchMethods | |
# Used in a DM model to provide o search method like SearchLogic | |
# class BlogPost | |
# include DataMapper::Resource | |
# extend DataMapper::Search::SearchMethods | |
# property :id, Serial | |
# property :created_on, Date | |
# end | |
# | |
# BlogPost.search('created_at.gt' => 2.days.ago, 'created_at.lte' => 1.day.ago) | |
# | |
# This seems generally useless, unless we consider the case of a form. | |
# - form_for @search do |f| | |
# f.date_select "created_on.gt", :include_blank => true | |
# f.date_select "created_on.lte", :inclued_blank => true | |
# f.submit "Filter" | |
# | |
# Then, in the controller: | |
# | |
# class BlogPostsController < ApplicationController | |
# def index | |
# @search = BlogPost.search(params[:search]) | |
# @blog_posts = @search.all | |
# end | |
# end | |
# | |
# Now that's pretty stylin' | |
def self.search(params={}) | |
SearchObject.new self, SearchMethods.parse_query_operators(params) | |
end | |
def self.parse_query_operators(params) | |
params.inject({}) do |memo, (key, value)| | |
memo[parse_query_operator(key)] = value | |
memo | |
end | |
end | |
def self.parse_query_operator(key) | |
property, operator = key.split('.') | |
operator ? property.to_sym.send(operator) : property | |
end | |
end | |
class SearchObject | |
def initialize(model, query_conditions) | |
@model, @query_conditions = model, query_conditions | |
end | |
def all | |
@model.all(@query_conditions) | |
end | |
def first | |
@model.first(@query_conditions) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment