Skip to content

Instantly share code, notes, and snippets.

@nathanpalmer
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanpalmer/1ea75cdc341eba1e25d5 to your computer and use it in GitHub Desktop.
Save nathanpalmer/1ea75cdc341eba1e25d5 to your computer and use it in GitHub Desktop.
Action separation for a controller
# Setup in a scenario way with perform the basic action that we have from base_actions controller
#
# Emulate or possibly just use the callbacks from within rails
# https://github.com/rails/rails/blob/master/actionpack/lib/abstract_controller/callbacks.rb
#
# This gives us the before_/after_/around_ filters along with a `run_callbacks` method
class BaseUpdateAction
def perform(method)
saved = each_from_parameters(params[collection_name]) do |model_hash|
# Need a way to get access to the model we're getting, but I haven't dug into the run_callbacks method
run_callbacks(:update) do
scope = get_scope(model_class, model_class, :update)
model = scope.find(key(model_hash))
model.assign_attributes(update_params(flatten_links(model_hash)))
model.save
model
end
end
# Then what if we need to override this part? One thought is that now that this action is it's own class this method could
# be broken up into several methods and each could be overridden if necessary.
if saved.nil?
head :no_content
elsif saved.any? { |item| item.errors.present? }
render json: { errors: saved.find { |item| item.errors.present? }.errors }, status: :unprocessable_entity
else
head :no_content
#render json: serializer.serialize(saved, current_context)
end
end
end
class BaseActionsController
def update
model = # get the model
# basically find out if there is a class defined, if it's there then execute any actions from it
show_action = "#{name}::Show".constantize
if show_action.present?
# If an override exists, use it
show_action.perform
else
# Otherwise execute the main action
BaseActionUpdate.perform
end
end
end
module Backer
# So we're inheriting from BaseUpdateAction so we get everything from that
# Hoping that much of what we'd need to do would come from callbacks in the very same
# way as controllers and models in rails.
class Update < BaseUpdateAction
before_save :do_something
def do_something(model)
model.prop = "1"
model
end
# However we could explore overrides for other things as well as mentioned a bit a bove
def return_data
render json: {}
end
end
end
class BackerController < BaseActionsController
## nothing done here
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment