Maksym Prokopov personal blog
Idea is a something worth sharing

How to improve ruby code with dup and tap methods

06.06.2018

Reading time: 1 min.

Here is a piece of my old code, but it’s definitely could be improved.

def to_params
  h = ticket_params
    h[:activity] = extract_activity if extract_activity
    h[:event] = extract_event if extract_event
    h.delete(:state_event)
    h.delete(:activities_attributes)
  h
end

As you can see here, ‘h’ variable name is quite uncommunicative. Could it be refactored?

Let’s see, h=ticket_params. We call this because we don’t want to modify ticket_params. Is there any method which creates a copy?

It turns out we have dup method which creates a copy of an object, this is exactly what we wanted. Then, we have tap method, which allows us to dive in object internals and return then itself. Here is whole new piece of code after refactoring.

def to_params
  ticket_params.dup.tap do |params|
    params[:activity] = extract_activity if extract_activity
    params[:event] = extract_event if extract_event
    params.delete(:state_event)
    params.delete(:activities_attributes)
  end
end

Much better now and we do not have any redundant variable!