module Linkr::Models class Link < Base PER_PAGE = 25 has_many :comments; has_many :votes validates_presence_of :user, :url, :title validates_uniqueness_of :url, :title attr_accessor :description def after_create comments.create :body => description, :user => user unless description.blank? Vote.for self.user, self, :up end class << self def find_all_by_score(tag=nil, page=1) timestamp_func = ActiveRecord::Base.connection.adapter_name == "MySQL" ? 'UNIX_TIMESTAMP' : 'julianday' find :all, :order => "round(#{timestamp_func}(created_at)) desc, score desc, created_at desc", :limit => PER_PAGE, :offset => (page-1)*page, :conditions => tag ? ["tags like ?", "%#{tag}%"] : nil end def find_all_by_date(tag=nil, page=1) find :all, :order => 'created_at desc', :limit => PER_PAGE, :offset => (page-1)*page, :conditions => tag ? ["tags like ?", "%#{tag}%"] : nil end def find_tags (Link.find(:all).collect { |l| l.tags.to_s.split }).flatten.uniq.sort end def search(query) (find(:all, :conditions => ['title LIKE ?', "%#{query}%"]) + Comment.find(:all, :conditions => ['body LIKE ?', "%#{query}%"]).collect(&:link)). uniq.sort_by(&:created_at).reverse end def tag_count(tag) Link.count :conditions => ["tags like ? ", "%#{tag}%"] end def tag_cloud cloud = {} find_tags.each do |tag| cloud[tag] = tag_count tag end cloud end end end class Comment < Base belongs_to :link validates_presence_of :link_id, :body, :user end class Vote < Base belongs_to :link def to_s; self.direction == 1 ? 'up' : 'down' end def after_save self.link.score += self.direction self.link.update end def self.for(user, link, direction) vote = Vote.find_by_user_and_link_id(user, link) dir = direction.to_sym == :up ? 1 : -1 if vote return if vote.direction == dir vote.update_attribute :direction, dir else Vote.create :user => user, :link => link, :direction => dir end end end class InitSchema < V 1 def self.up create_table :linkr_links do |t| t.column :title, :string, :limit => 100 t.column :url, :string, :limit => 255 t.column :tags, :string t.column :user, :string t.column :score, :integer, :default => 0 t.column :created_at, :datetime end create_table :linkr_comments do |t| t.column :link_id, :integer t.column :user, :string t.column :created_at, :datetime t.column :body, :text end create_table :linkr_votes do |t| t.column :user, :string t.column :link_id, :integer t.column :direction, :integer end end end end