Created
January 20, 2014 16:06
-
-
Save krisleech/8522918 to your computer and use it in GitHub Desktop.
Automatic mapping of event to controller actions
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 RegisterInterestController < ApplicationController | |
skip_before_filter :ensure_logged_in | |
def create | |
@interest_form = RegisterInterest::InterestForm.new(form_params) | |
register_interest = RegisterInterest.new | |
register_interest.subscribe(EventResponser.new(self)) | |
register_interest.with_form(@interest_form) | |
end | |
private | |
def form_params | |
params[:interest_form] | |
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
# maps events to controller actions, for example if the publisher (RegisterInterest) broadcast an | |
# "register_interest_successful" event then the "success" action would be rendered. | |
class EventResponser | |
def initialize(controller) | |
@controller = controller | |
end | |
def respond_to?(method_name) | |
%w(success failed).any? { |word| method_name.to_s.include?(word) } || super | |
end | |
def method_missing(method_name, *args, &block) | |
if method_name.to_s.downcase.include?('success') | |
@controller.render(:action => :success) | |
elsif method_name.to_s.downcase.include?('failed') | |
@controller.render(:action => :failed) | |
else | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment