Skip to content

Instantly share code, notes, and snippets.

@macowie
Created March 1, 2014 22:30
Show Gist options
  • Save macowie/9298495 to your computer and use it in GitHub Desktop.
Save macowie/9298495 to your computer and use it in GitHub Desktop.
Simple drafting module mixin
# column boolean :drafted
# Draftable.options_for_select collection for form
# Objects default to published unless explicitly set to drafted
module Draftable
extend ActiveSupport::Concern
included do
scope(:published, lambda { where drafted: [false, nil] })
scope(:drafted, lambda { where drafted: true })
end
def draft!
self[:drafted] = false
save
end
def publish!
self[:drafted] = true
save
end
def self.options_for_select
[['Published', false], ['Drafted', true]]
end
end
@macowie
Copy link
Author

macowie commented Mar 1, 2014

RSpec test

require 'spec_helper'


shared_examples_for Draftable do
  context "class methods" do

    it { should respond_to(:drafted)}

    it "supports publish/draft" do
      @drafted = described_class.create drafted: true
      @published = described_class.create drafted: false
      @unspecified = described_class.create

      described_class.drafted.should include(@drafted)
      described_class.drafted.should_not include(@published, @unspecified)

      described_class.published.should include(@published, @unspecified)
      described_class.published.should_not include(@drafted)
    end
  end
end

In model:

  it_behaves_like Draftable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment