Skip to content

Instantly share code, notes, and snippets.

@billturner
Created September 21, 2009 20:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save billturner/190547 to your computer and use it in GitHub Desktop.
Save billturner/190547 to your computer and use it in GitHub Desktop.
class Post
attr_accessor :taglist
include DataMapper::Resource
property :id, Serial
property :title, String, :length => 255
property :slug, String, :length => 255
property :body, Text
property :published, Boolean, :default => false
property :published_at, DateTime
property :created_at, DateTime
property :updated_at, DateTime
has n, :taggings
has n, :tags, :through => :taggings
before :save, :determine_publish_status
after :create, :generate_slug
after :create, :assign_tags
after :update, :update_tags
private
class << self
def recent_published
self.all(:published => true, :order => [:published_at.desc], :limit => 10)
end
end
def generate_slug
self.update(:slug => "#{title.gsub(/[^a-z0-9]+/i, '-').gsub(/-$/, '').downcase}")
end
def determine_publish_status
self.update(:published_at => Time.now) if published? && published_at.blank?
end
def assign_tags
self.taglist.split(',').collect { |t| t.strip }.uniq.each do |tag|
current_tag = Tag.first_or_create(:name => tag.downcase)
self.tags << current_tag
end
end
def update_tags
self.taggings.each { |tagging| tagging.destroy }
self.taggings.reload
assign_tags
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment