Skip to content

Instantly share code, notes, and snippets.

@RStankov
Created July 8, 2012 21:35
Show Gist options
  • Save RStankov/3072932 to your computer and use it in GitHub Desktop.
Save RStankov/3072932 to your computer and use it in GitHub Desktop.
hexagonal rails try
class ArticlesController < ApplicationController
def create
PublishArticle.publish(current_user, params[:article]) do |result|
result.success { |article| redirect_to article_path(article) }
result.failure { |article| @article = article; render :new }
end
end
end
require 'spec_helper'
describe ArticlesController do
stub_loggged_user
describe "POST create" do
def result(result, *args)
ServiceResult.new(result, *args)
end
let(:article) { stub_model(Article) }
it "publishes a article" do
PublishArticle.should_receive(:publish).with(current_user, 'these' => 'params').and_yield result(:success, article)
post :create, :article => {'these' => 'params'}
end
it "redirects to article on success" do
PublishArticle.stub(:publish).and_yield result(:success, article)
post :create
controller.should redirect_to article_path(article)
end
it "renders new action on failure" do
PublishArticle.stub(:publish).and_yield result(:failure, article)
post :create
controller.should assign_to(:artilce).with(article)
controller.should render_template :new
end
end
end
module PublishArticle
extend self
def publish(author, attributes)
article = Article.new(params)
article.author = author
result = article.save ? :success : :failure
ServiceResult.new result, article
end
end
module Service
class Result < BlankObject
def initialize(result, args)
@result = result
@args = args
end
def method_missing(method)
if @result == method
yield *@args
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment