Module: Publishable::ClassMethods

Defined in:
lib/publishable.rb

Instance Method Summary collapse

Instance Method Details

#publishable(options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/publishable.rb', line 9

def publishable(options = {})
  column_name = (options[:on] || :published_at).to_s

  if respond_to?(:scope)
    scope :published, lambda { |time = Time.now|
      where("#{column_name} IS NOT NULL AND #{column_name} <= ?", time.utc)
    }

    scope :unpublished, lambda { |time = Time.now|
      where("#{column_name} IS NULL OR #{column_name} > ?", time.utc)
    }
  end
  
  class_eval <<-EVIL, __FILE__, __LINE__ + 1
    def published?(time = Time.now)
      #{column_name} ? #{column_name} <= time : false
    end

    def publish(time = Time.now)
      self.#{column_name} = time unless published?(time)
    end

    def publish!(time = Time.now)
      publish(time) && (!respond_to?(:save) || save)
    end        
  EVIL
end