Create a gist now

Instantly share code, notes, and snippets.

@hosh /let.rb
Created Jun 25, 2010

What would you like to do?
# app/concerns/let.rb
# Ripped from Rspec 2.0 beta.12
# I've found it so useful in Rspec, I made it into a module. Controller code with shared
# code seem to have a lot of use for this. For example, in inherited_resources, you would
# typically override model, parent, etc. to configure it. You would typically memomize it
# as well. With this, you can use a more compact let() syntax.
# (Note: This code will only work in Rails 3)
module Let
extend ActiveSupport::Concern
included do
extend Let::ClassMethods
end
private
def __memoized # :nodoc:
@__memoized ||= {}
end
module ClassMethods
def let(name, &block)
define_method(name) do
__memoized[name] ||= instance_eval(&block)
end
protected(name)
end
end
end
module Admin
class CustomersController < ApplicationController
include Controllers::AdminSharedCode
let(:model) { Customers.by_owner(current_user) }
let(:target_ids) { params[:targets] }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment