Skip to content

Instantly share code, notes, and snippets.

@cavalle

cavalle/post.rb Secret

Created February 4, 2013 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cavalle/16e650becb46d4e22f15 to your computer and use it in GitHub Desktop.
Save cavalle/16e650becb46d4e22f15 to your computer and use it in GitHub Desktop.
“Object on Rails” example refactored (models only)
class Post < ActiveRecord::Base
include Taggable
validates :title, presence: true
before_create :set_defaults
scope :most_recent, ->{ order('pubdate DESC').limit(10) }
def picture?
image_url.present?
end
def prev
Post.order('pubdate DESC').where('pubdate < ?', pubdate).first
end
def next
Post.order('pubdate ASC').where('pubdate > ?', pubdate).first
end
private
def set_defaults
self.pubdate ||= Time.now
self.body ||= 'Nothing to see here'
end
end
class Tag < ActiveRecord::Base
scope :alphabetical, ->{ order(:name) }
end
module Taggable
extend ActiveSupport::Concern
included do
has_many :taggings
has_many :tags, through: :taggings
scope :tagged_with, ->(tag_name) do
joins(:tags).where(tags: { name: tag_name })
end
end
def tag_list
tags.pluck(:name).join(', ')
end
def tag_list=(tag_list)
assign_tag_list tag_list
end
private
def assign_tag_list(tag_list)
tag_names = tag_list.split(',').map(&:strip).uniq
self.tags = tag_names.map do |tag_name|
Tag.where(name: tag_name).first_or_initialize
end
end
end
class Tagging < ActiveRecord::Base
belongs_to :article
belongs_to :tag
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment