Skip to content

Instantly share code, notes, and snippets.

@mattsnyder
Created June 4, 2013 13:04
Show Gist options
  • Select an option

  • Save mattsnyder/5705739 to your computer and use it in GitHub Desktop.

Select an option

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
#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
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
class MyOrdersController < ApplicationController
expose :orders
def open
self.orders = OrdersRepository.find_open
end
end
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
@mattsnyder

Copy link
Copy Markdown
Author

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.

  expose :value1, :value2, :etc
  expect(controller).to expose(some_value).as(variable_name)

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