Skip to content

Instantly share code, notes, and snippets.

@avdi
Created September 20, 2012 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avdi/3757036 to your computer and use it in GitHub Desktop.
Save avdi/3757036 to your computer and use it in GitHub Desktop.
Experimental syntax sugar for focused_controller
require 'focused_controller/controller'
module BitBindery
BenefitsController = FocusedController::Controller.new do
common do
expose(:product) { @product ||= shop.product_for_id(params[:product_id]) }
expose(:benefits) { @benefits ||= product.benefits }
expose(:benefit)
end
action :index do
end
action :show do
def call
@benefit = benefits.get(params[:id])
end
end
action :new do
expose(:benefit_setup) { product.new_benefit_setup(params['benefit'], current_user) }
def call
render "bit_bindery/benefits/setup/#{benefit_setup.type_id}"
end
end
action :create do
def call
@benefit = product.add_benefit(params[:benefit])
redirect_to(product_benefits_path(product))
end
end
end
end
module FocusedController
class Controller < Module
def initialize(base_class = ::ApplicationController)
@controller_base_class = base_class
super()
end
private
attr_reader :controller_base_class
# Define the local Action base class
def common(&body)
action_base_class_body_blocks << body
end
def action(name, &body)
class_name = name.to_s.camelize
action_class = Class.new(action_base_class, &body)
const_set(class_name, action_class)
end
def action_base_class
body_blocks = action_base_class_body_blocks
container = self
@action_base_class ||= Class.new(controller_base_class) do
container.const_set :Action, self
include FocusedController::Mixin
def run(*args)
call(*args)
end
def call; end
body_blocks.each do |body|
module_eval(&body)
end
end
end
def action_base_class_body_blocks
(@action_base_class_body_blocks ||= [])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment