Last active
June 12, 2017 13:47
-
-
Save mpugach/ccba8fe86614714ee15fba2ee421d338 to your computer and use it in GitHub Desktop.
Active interaction controller
This file contains hidden or 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
module Api | |
module V1 | |
class ActivitiesController < Api::V1::ApplicationController | |
render_interactions :create, :update, :show, :destroy | |
end | |
end | |
end |
This file contains hidden or 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
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