Skip to content

Instantly share code, notes, and snippets.

@nicholasjhenry
Created July 3, 2012 14:29
Show Gist options
  • Select an option

  • Save nicholasjhenry/3040068 to your computer and use it in GitHub Desktop.

Select an option

Save nicholasjhenry/3040068 to your computer and use it in GitHub Desktop.
ActiveRecord Refactoring with Scopes
class NewsItem
scope :news_items, where(flag_news: true).order("publish_date DESC")
scope :press_releases, lambda { where(flag_news: false).order("publish_date DESC") }
scope :news_items_homepage, where(flag_news: true, featured: true).order("publish_date DESC")
scope :press_releases_homepage, lambda { where(flag_news: false, featured: true).order("publish_date DESC") }
end
def home
@news_items = NewsItem.news_items.limit(RefinerySetting.find_or_set(:homepage_news_items, 4))
@press_releases = NewsItem.press_releases_homepage.limit(RefinerySetting.find_or_set(:homepage_press_releases, 4))
end
class NewsItem
scope :sorted, order("publish_date DESC")
scope :news_items, where(flag_news: true)
scope :press_releases, where(flag_news: false)
scope :featured, where(featured: true)
scope :top, lambda {|l| limit(l)}
def self.find_all_news_items
news_items.sorted
end
def self.find_all_press_releases
press_releases.sorted
end
def self.find_featured_news_items(limit=4)
news_items.featured.sorted.top(limit)
end
def self.find_featured_press_releases(limit=4)
press_releases.featured.sorted.top(limit)
end
end
def home
@news_items = find_featured_news_items
@press_releases = find_featured_press_releases
end
private
def find_featured_news_items
NewsItem.find_featured_news_items(limit(:home_news_items))
end
def find_featured_press_releases
NewsItem.find_featured_press_releases(limit(:home_press_releases))
end
def limit(key)
RefinerySetting.find_or_set(key, default_limit)
end
def default_limit
4
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment