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
1 Answer 1
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.
-
2\$\begingroup\$ I would advise using
public_send
instead ofsend
. \$\endgroup\$Jordan– Jordan2016年08月16日 14:24:07 +00:00Commented Aug 16, 2016 at 14:24