Created
April 28, 2011 16:01
-
-
Save bernerdschaefer/946635 to your computer and use it in GitHub Desktop.
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
module Padrino | |
# Minimal version of `decent_exposure`[1], in keeping with Padrino's | |
# simplicity. | |
# | |
# [1] https://github.com/voxdolo/decent_exposure | |
# | |
# == Usage | |
# | |
# The first step is to register the plugin with your application: | |
# | |
# MyApp.register Padrino::Expose | |
# | |
# Then use the `expose` method in your controllers to, well, | |
# expose the sorts of things you would usually use an instance | |
# variable for. | |
# | |
# MyApp.controllers :dashboard do | |
# expose(:stats) { Stat.all } | |
# expose(:site) { Site.find(params[:site_id]) } | |
# | |
# get :index do | |
# if current_account.site != site | |
# redirect url("/") | |
# else | |
# render :index | |
# end | |
# end | |
# end | |
# | |
# You can also access the resources from your views! | |
# | |
# # views/dashboard/index.slim | |
# - stats.each do |stat| | |
# p == stat.total | |
# | |
module Expose | |
class << self | |
def registered(app) | |
app.extend ClassMethods | |
end | |
alias :included :registered | |
end | |
module ClassMethods | |
# Defines a helper method for your controllers and views using the name | |
# you provide. Its return value will be the result of the block provided, | |
# and will be memoized in an instance variable of the same name. | |
# | |
# @param name the name for this exposure | |
# @param block the block to memoize | |
def expose(name, &block) | |
ivar = :"@#{name}" | |
define_method name do | |
if instance_variable_defined?(ivar) | |
instance_variable_get(ivar) | |
else | |
instance_variable_set(ivar, instance_eval(&block)) | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment