Skip to content

Commit

Permalink
use multiget to minimize database calls
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Wiggins committed Jul 1, 2009
1 parent b40d08f commit 7d5c33a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
22 changes: 13 additions & 9 deletions lib/post.rb
Expand Up @@ -24,26 +24,30 @@ def initialize(params={})


class RecordNotFound < RuntimeError; end class RecordNotFound < RuntimeError; end


def self.find_by_slug(slug) def self.new_from_json(json)
json = DB[db_key_for_slug(slug)]
raise RecordNotFound unless json raise RecordNotFound unless json
new JSON.parse(json) new JSON.parse(json)
end end


def self.new_from_slugs(slugs)
ids = slugs.map { |slug| db_key_for_slug(slug) }
DB.mget(ids).map { |json| new_from_json(json) }
end

def self.find_by_slug(slug)
new_from_json DB[db_key_for_slug(slug)]
end

def self.find_range(start, len) def self.find_range(start, len)
DB.list_range(chrono_key, start, start + len - 1).map do |slug| new_from_slugs DB.list_range(chrono_key, start, start + len - 1)
find_by_slug(slug)
end
end end


def self.all def self.all
find_range(0, 9999999) find_range(0, 9999999)
end end


def self.all_tagged(tag) def self.find_tagged(tag)
DB.list_range("#{self}:tagged:#{tag}", 0, 99999).map do |slug| new_from_slugs DB.list_range("#{self}:tagged:#{tag}", 0, 99999)
find_by_slug(slug)
end
end end


def self.db_key_for_slug(slug) def self.db_key_for_slug(slug)
Expand Down
2 changes: 1 addition & 1 deletion main.rb
Expand Up @@ -60,7 +60,7 @@ def auth


get '/past/tags/:tag' do get '/past/tags/:tag' do
tag = params[:tag].downcase.strip tag = params[:tag].downcase.strip
posts = Post.all_tagged(tag) posts = Post.find_tagged(tag)
@title = "Posts tagged #{tag}" @title = "Posts tagged #{tag}"
erb :tagged, :locals => { :posts => posts, :tag => tag } erb :tagged, :locals => { :posts => posts, :tag => tag }
end end
Expand Down

0 comments on commit 7d5c33a

Please sign in to comment.