-
-
Save cavalle/16e650becb46d4e22f15 to your computer and use it in GitHub Desktop.
“Object on Rails” example refactored (models only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tag < ActiveRecord::Base | |
scope :alphabetical, ->{ order(:name) } | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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