Skip to content

Instantly share code, notes, and snippets.

@bootcoder
Created November 11, 2019 18:47
Show Gist options
  • Save bootcoder/2b3db05d4d8fc9f80e5e022b8f02279d to your computer and use it in GitHub Desktop.
Save bootcoder/2b3db05d4d8fc9f80e5e022b8f02279d to your computer and use it in GitHub Desktop.
DRY up named arguments
# frozen_string_literal: true
class Api::V2::Users::UsersController < Api::V2::BaseController
soft_authentication :current
def current
user_json = ActiveModelSerializers::SerializableResource.new(current_user,{show_subscriptions: true}).as_json
raise AuthorizationError unless current_user
render json: user_json, status: :ok, show_subscriptions: true
rescue AuthorizationError
render json: {}, status: :ok
rescue Net::OpenTimeout, Braintree::ServerError
# Note this resuce / method combo can be removed when the userbase is off braintree.
# Note this error won't occur if we don't have a current user, so we use it safely
# These errors potentially occur when calling .active_through_date
user_json[:user]['next_expiring_sub'] = next_expiring_sub(current_user)
render json: user_json, status: :ok, show_subscriptions: true
end
def update
update_user_from_params
if current_user.errors.any?
errors = current_user.errors[:base].to_sentence
errors = current_user.errors.full_messages if errors.empty?
render json: { errors: errors }, status: :unprocessable_entity
else
reset_login_timestamp_cookie
user_json = ActiveModelSerializers::SerializableResource.new(current_user,{show_subscriptions: true}).to_json
render json: user_json, status: :accepted
end
end
protected
def update_user_from_params
begin
if update_params[:email]
UserUpdater.new(current_user).update(
email: update_params[:email],
rivals_emails: update_params[:rivals_emails].to_i == 1,
third_party_emails: update_params[:third_party_emails].to_i == 1
)
else
UserUpdater.new(current_user).update(
rivals_emails: update_params[:rivals_emails].to_i == 1,
third_party_emails: update_params[:third_party_emails].to_i == 1
)
end
rescue => e
Rails.logger.error e
raise e if e.class == Rack::Timeout::RequestTimeoutException
raise e if e.class == ActionController::ParameterMissing
current_user.errors.add(:base, 'Could not update profile!')
current_user.reload
end
end
def update_params
params.require(:user).permit(:email, :rivals_emails, :third_party_emails)
end
# ROUNDUP Is this still required in a BT free world?
# Note this method is a fallback that doesn't depend on braintree
def next_expiring_sub(current_user)
newest_expiration = 0
current_user.subscriptions.select { |s| s.active? }.inject(newest_expiration) do |newest_exp, s|
sub_exp_date = s.estimated_next_billing_date.to_time.to_i
sub_exp_date > newest_exp ? sub_exp_date : newest_exp
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment