Skip to content

Instantly share code, notes, and snippets.

@zhangyuan
Last active December 11, 2015 03:19
Show Gist options
  • Save zhangyuan/4537052 to your computer and use it in GitHub Desktop.
Save zhangyuan/4537052 to your computer and use it in GitHub Desktop.
module Model
module Publishable
PUBLISHING_STATUSES = %w(published approved deleted).freeze
extend ActiveSupport::Concern
included do
PUBLISHING_STATUSES.each do |status|
define_method "is_#{status}?" do
self.publishing_status == status
end
end
validates :publishing_status, inclusion: PUBLISHING_STATUSES
scope :published_as, (Proc.new do |*statuses|
where(publishing_status: fetch_publishing_status_ids(*statuses))
end)
end
module ClassMethods
def fetch_publishing_status_ids(*args)
args.map {|status| PUBLISHING_STATUSES.index(status.to_s)}
end
def fetch_publishing_statuses(*args)
args.map {|status_id| PUBLISHING_STATUSES.at status_id}
end
end
def publishing_status=(status)
status_id = self.class.fetch_publishing_status_ids(status).first
write_attribute(:publishing_status, status_id)
end
def publishing_status
self.class.fetch_publishing_statuses(read_attribute(:publishing_status)).first
end
def destroy(force = false)
if force
super()
else
self.publishing_status = :deleted
self.save
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment