公開フラグの立ってるものだけを取るのをうまいこと書きたかったので、acts_as_paranoidをまねて作ってみた。
:disabled
はコントローラから有効無効を制御する用。
(↑ユーザー権限が管理者のときは全部出したいなどという目的)
Rails素人にはこれが限界。
ActsAsPublishable
module ActsAsPublishable
thread_mattr_accessor :disabled
module Publishable
def published?
self.published_at.present?
end
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def published_default_scope
return nil if ActsAsPublishable.disabled
self.all.table[:published_at].not_eq(nil)
end
def with_unpublished
without_published_default_scope
end
protected
def without_published_default_scope
scope = self.all
scope = scope.unscope(where: published_default_scope)
# Fix problems with unscope group chain
scope = scope.unscoped if scope.to_sql.include? published_default_scope.to_sql
scope
end
end
end
def acts_as_publishable(options = {})
include ActsAsPublishable::Publishable
default_scope { where(published_default_scope) }
end
end
# Extend ActiveRecord's functionality
ActiveRecord::Base.send :extend, ActsAsPublishable