1
0

More than 3 years have passed since last update.

ActsAsPublishable 作ってみた

Posted at

公開フラグの立ってるものだけを取るのをうまいこと書きたかったので、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
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0