Created
June 4, 2013 13:04
-
-
Save mattsnyder/5705739 to your computer and use it in GitHub Desktop.
In an attempt to clarify what the controller makes available to views instead of guessing, identify them with #expose
This file contains 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
#Include this method in your application_controller.rb | |
def self.expose(*variable_names) | |
variable_names.each do |variable_name| | |
define_method((variable_name.to_s+"=").to_sym) do |value| | |
@exposed ||= Hash.new | |
@exposed[variable_name]= value | |
end | |
private (variable_name.to_s+"=").to_sym | |
define_method(variable_name) do | |
@exposed ||= Hash.new | |
Maybe(@exposed[variable_name]) | |
end | |
helper_method variable_name | |
end | |
end |
This file contains 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 'rspec/given' | |
describe MyOrdersController | |
describe "#open" do | |
context "when the orders repository finds a few orders" do | |
Given (:array_of_orders) { mock } | |
Given { OrdersRepository.stub(:find_open).and_return(array_of_orders) } | |
When { get :open } | |
Then { expect(controller).to expose(array_of_orders).as(:orders) } | |
end | |
end | |
end |
This file contains 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 MyOrdersController < ApplicationController | |
expose :orders | |
def open | |
self.orders = OrdersRepository.find_open | |
end | |
end |
This file contains 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
RSpec::Matchers.define :expose do |value| | |
match do |actual| | |
actual.send(@getter) == value | |
end | |
chain :as do |getter| | |
@getter = getter | |
end | |
failure_message_for_should do | |
"should have exposed #{value} to the view as '#{@getter}'" | |
end | |
failure_message_for_should_not do | |
"should not have exposed #{value} as '#{@getter}'" | |
end | |
description do | |
"should expose #{value} to the view as '#{@getter}'" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not entirely happy with the implementation of the
expose
method, but it works for now. The spec matcher and usage capture the essence of what I am trying to achieve.