Skip to content

Instantly share code, notes, and snippets.

@alexvbush
Created July 14, 2014 02:06
Show Gist options
  • Save alexvbush/7a7f30dda86be6b82a72 to your computer and use it in GitHub Desktop.
Save alexvbush/7a7f30dda86be6b82a72 to your computer and use it in GitHub Desktop.
Final version of Article model.
class Article < ActiveRecord::Base
include Categorizable
APPROVED = 'approved'
PENDING = 'pending'
REJECTED = 'rejected'
attr_accessible :approved_at, :url, :body, :image, :rating, :state, :title, :news_source_id, :published_at
validates :url, :uniqueness => true
validates :rating, :inclusion => { :in => (0..10) }
validates :title, :presence => true
mount_uploader :image, PhotoUploader
belongs_to :news_source
def self.for_state(state)
if state == PENDING
pending
elsif state == APPROVED
approved
elsif state == REJECTED
rejected
else
scoped
end
end
def self.for_search_query(query, include_categories = true)
return scoped if query.blank?
if include_categories
with_categories.where('title LIKE ? OR categories.name LIKE ?', "%#{query}%", "%#{query}%")
else
where('title LIKE ?', "%#{query}%")
end
end
def self.with_categories
includes(:categories)
end
def self.order_for_state(state)
case state
when APPROVED
order('articles.approved_at DESC')
when PENDING
order('articles.published_at')
else
order('articles.created_at DESC')
end
end
def self.pending
where(state: PENDING)
end
def self.approved
where(state: APPROVED)
end
def state=(value)
if value == APPROVED
write_attribute :approved_at, DateTime.now if state != APPROVED
else
write_attribute :approved_at, nil
end
write_attribute(:state, value)
end
def approve
self.state = APPROVED
self.approved_at = DateTime.now
end
def reject
self.state = REJECTED
self.approved_at = nil
end
def enqueue
self.state = PENDING
self.approved_at = nil
end
def approve!
approve
save
end
def reject!
reject
save
end
def enqueue!
enqueue
save
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment