Skip to content

Instantly share code, notes, and snippets.

@lucasrenan
Last active December 14, 2015 20:48
Show Gist options
  • Save lucasrenan/5146022 to your computer and use it in GitHub Desktop.
Save lucasrenan/5146022 to your computer and use it in GitHub Desktop.
query object example
def index
@posts = PublishedQuery.new(self, Post).published
end
class PublishedQuery
def initialize(controller, model)
@controller = controller
@model = model
end
def criteria
@model.criteria
end
def published
@controller.user_signed_in? ? criteria.all : criteria.published
end
end
require "spec_helper"
describe PublishedQuery do
let(:controller) { mock(PostsController) }
let(:model) { Post }
subject { PublishedQuery.new(controller, model) }
describe ".criteria" do
it "returns a model criteria" do
expect(subject.criteria).to eq(model.criteria)
end
end
describe ".published" do
context "when user is logged in" do
before do
controller.stub(:user_signed_in?) { true }
end
it "returns criteria 'all'" do
expect(subject.published).to eq(model.all)
end
end
context "when user is not logged in" do
before do
controller.stub(:user_signed_in?) { false }
end
it "returns criteria 'published'" do
expect(subject.published).to eq(model.published)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment