1
\$\begingroup\$

I wish to get rid of using switch case with statuses twice in my code. But create_message function will be bigger in the future, so must stay and I don't want to create messages in send_user_push_notification directly.

Any ideas?

def send_user_push_notification(order, parse_events)
 now = Time.zone.now
 case parse_events
 when 'pending'
 if send_push_notification(order.shopper_id, order, parse_events)
 order.shopper_notified_at = now
 end
 when 'handed_over'
 if send_push_notification(order.deliverer_id, order, parse_events)
 order.deliverer_notified_at = now
 end
 end
end
def send_push_notification(user_id, order, parse_events)
 Parse.publish_order_status(
 user_id,
 *parse_events,
 create_message(order, parse_events)
 )
end
def create_message(order, parse_events)
 case parse_events
 when 'pending'
 I18n.t('orders.shopper.message')
 when 'handed_over'
 I18n.t(
 'orders.deliverer.message',
 order_id: order.order_id,
 store_id: order.store_id
 )
 end
end
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Aug 16, 2016 at 12:40
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You could split the two decisions, for instance:

# Outside your method 
EVENT_TO_USERKIND = { pending: 'shopper', handed_over: :'deliverer' }
# Now inside your method 
user_kind = EVENT_TO_UID_METHOD[parse_events]
if user_kind && send_push_notification(order.send("#{user_kind}_id"), order, parse_events)
 order.send("#{user_kind}_notified_at=", now)
end

It's more compact and concise, but the usage of send might be considered ugly, and it depends on naming convention (do not dare to rename deliverer_notified_at to delivery_guy_notified_at!), so you have to choose whether or not you like it.

answered Aug 16, 2016 at 14:16
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I would advise using public_send instead of send. \$\endgroup\$ Commented Aug 16, 2016 at 14:24

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.