Skip to content

Instantly share code, notes, and snippets.

@mpugach
Last active June 12, 2017 13:47
Show Gist options
  • Save mpugach/ccba8fe86614714ee15fba2ee421d338 to your computer and use it in GitHub Desktop.
Save mpugach/ccba8fe86614714ee15fba2ee421d338 to your computer and use it in GitHub Desktop.
Active interaction controller
module Api
module V1
class ActivitiesController < Api::V1::ApplicationController
render_interactions :create, :update, :show, :destroy
end
end
end
module Api
module V1
class ApplicationController < ::ApplicationController
class << self
private
def render_interactions(*actions)
actions.each do |action|
define_method(action) do
render_interaction(
"#{self.class.name.sub(/Controller$/, '')}::#{action.to_s.titleize}Interaction".constantize
)
end
end
end
end
private
def render_interaction(
klass,
success: ->(int) { render json: int.result },
failure: ->(int) { render json: int.serialized_errors, location: false, status: :unprocessable_entity }
)
interaction = klass.run(interaction_params)
(interaction.valid? ? success : failure)[interaction]
end
def interaction_params
params
.permit!
.to_h
.deep_transform_keys(&:underscore)
.merge(current_user: current_user)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment