How to decorates date format for 3 different fields using Draper decorator gem

527 views Asked by At

I want to decorate my 3 dates using a decorator pattern, I did what steps are necessary for implementing the decorator pattern, I have written following code in the decorator to decorates my date fields

def date1
  model.date1.strftime("%d-%m-%y")
end

def date2
  model.date2.strftime("%d-%m-%y")
end

def date3
  model.date3.strftime("%d-%m-%y")
end

and View I am calling in following way

= @example.date1
= @example.date2
= @example.date3

So all the methods written in the above decorators are doing the same task, so i refactored that and one base decorator which contains only one format method, so the above decorator inherits from base decorator

Like

class BaseDecorator < Draper::Decorator

  def format_date(model_name, attribute_name)
    model_name.attributes[attriburte_name].strftime("%d-%m-%Y")
  end
end

and my sub decorator is looking like this

class ExampleDecorator < BaseDecorator

  def date1
    format_date(model, "date1")
  end
  def date2
    format_date(model, "date2")
  end
  def date3
    format_date(model, "date3")
  end
end

So now my question is in the sub decorator the same code is repeating so I want to refactor my code, how should i refactor my code?

1

There are 1 answers

0
QMFNP On

You can refactor this similarly to how you did in the BaseDecorator class:

class ExampleDecorator < BaseDecorator
  def formatted_date(attribute_name)
    format_date(model, attribute_name)
  end
end

And in your view:

<%= @example.formatted_date("date1") %>