Last active
December 14, 2015 20:48
-
-
Save lucasrenan/5146022 to your computer and use it in GitHub Desktop.
query object example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def index | |
| @posts = PublishedQuery.new(self, Post).published | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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