Skip to content

Instantly share code, notes, and snippets.

@JAMSUPREME
Created July 22, 2016 15:30
Show Gist options
  • Save JAMSUPREME/5084cf11cd7174ae7db43a5d1bdd2dc6 to your computer and use it in GitHub Desktop.
Save JAMSUPREME/5084cf11cd7174ae7db43a5d1bdd2dc6 to your computer and use it in GitHub Desktop.
Introducing improvements
# Introducing Commands
# The controller is still bloated, but we'll solve that problem later
# Here we pull all of the "business logic" into useful abstractions so the controller is easy to read and maintain
class Admin::AdminController < ApplicationController
before_action :redirect_unless_admin
def index
render 'index'
end
def menu
render 'upload_menu'
end
def upload_menu
# File reader is now something generic (an obvious and easy improvement)
new_file = FileReader.from_request(:new_menu)
# We've now pulled the operation into a "command" that will encapsulate everything we want to do
@result = UploadMenuCommand.execute(new_file)
if (@result.successful?)
render 'upload_menu'
else
redirect_to 'error'
end
end
def approve_events
# If you are OK with several commands doing reads on the same object, it may look like this (heavier command)
@result = EventsRequiringApprovalCommand.execute
if (@result.successful?)
render 'approve-events'
else
redirect_to 'error'
end
end
def review_event
event_id = params[:id]
# Here I propose an alternative if you do not "redundant" commands that are all reading the same object
finder = ProposedEventFinder.by_id(event_id)
currency_formatter = CurrencyFormatter.new('en-US') # this would likely come from browser or a config of some sort
@result = GetEventCommand.execute(finder, currency_formatter)
if (@result.successful?)
render 'review-event'
else
redirect_to 'error'
end
end
def complete_review_event
finder = ProposedEventFinder.by_id(event_id)
proposed_event = GetEventCommand.execute(finder)
if (params[:approve])
@result = ApproveEventCommand.execute(proposed_event)
else
@result = RejectEventCommand.execute(proposed_event)
end
if (@result.successful?)
redirect_to admin_approve_events_path
else
redirect_to 'error'
end
end
def redirect_unless_admin
redirect_to '/login?forbidden=t' unless session['logged-in'] == true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment