public
Created

How do I optimize the queries for this?

  • Download Gist
post.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
class Post < ActiveRecord::Base
before_create :update_counters!
def update_counters!
now = Time.zone.now
%w(draft published).each do |status|
[nil, "site_scoped", "category_scoped"].each do |scoping|
# "", "site_scoped_", "category_scoped_"
scoping = scoping.nil? ? "" : "#{scoping}_"
# last_published_post, etc.
post = send("#{scoping}last_#{status}_post")
if post.present? && now >= post.created_at
# seconds_since_last_published_post
self.send("#{scoping}seconds_since_last_#{status}_post=", (now - post.created_at).to_i)
end
end
end
end
%w(draft published).each do |status|
class_eval %{
def last_#{status}_post
@last_#{status}_post ||= ::Post.first(:order => "created_at desc", :conditions => {:user_id => user_id, :status => "#{status}"})
end
def category_scoped_last_#{status}_post
@category_scoped_last_#{status}_post ||= ::Post.first(:order => "created_at desc", :conditions => {:user_id => user_id, :status => "#{status}", :category_id => category_id})
end
def site_scoped_last_#{status}_post
@site_scoped_last_#{status}_post ||= ::Post.first(:order => "created_at desc", :conditions => {:user_id => user_id, :status => "#{status}", :site_id => site_id})
end
}
end
def last_post
unless @last_post.present?
if last_draft_post && last_published_post
@last_post = last_draft_post.id > last_published_post.id ? last_draft_post : last_published_post
else
@last_post = last_draft_post || last_published_post
end
end
@last_post
end
def site_scoped_last_post
unless @site_scoped_last_post.present?
if site_scoped_last_draft_post && site_scoped_last_published_post
@site_scoped_last_post = site_scoped_last_draft_post.id > site_scoped_last_published_post.id ? site_scoped_last_draft_post : site_scoped_last_published_post
else
@site_scoped_last_post = site_scoped_last_draft_post || site_scoped_last_published_post
end
end
@site_scoped_last_post
end
def category_scoped_last_post
unless @category_scoped_last_post.present?
if category_scoped_last_draft_post && category_scoped_last_published_post
@category_scoped_last_post = category_scoped_last_draft_post.id > category_scoped_last_published_post.id ? category_scoped_last_draft_post : category_scoped_last_published_post
else
@category_scoped_last_post = category_scoped_last_draft_post || category_scoped_last_published_post
end
end
@category_scoped_last_post
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.