Ruby on rails 4 如何使用Draper decorator gem装饰3个不同字段的日期格式

Ruby on rails 4 如何使用Draper decorator gem装饰3个不同字段的日期格式,ruby-on-rails-4,decorator,draper,Ruby On Rails 4,Decorator,Draper,我想使用装饰器模式装饰我的3个日期,我做了实现装饰器模式所需的步骤,我在装饰器中编写了以下代码来装饰我的日期字段 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 我是用下面的方式打电话的 = @example.date1 = @example.da

我想使用装饰器模式装饰我的3个日期,我做了实现装饰器模式所需的步骤,我在装饰器中编写了以下代码来装饰我的日期字段

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
我是用下面的方式打电话的

= @example.date1
= @example.date2
= @example.date3
因此,在上面的decorator中编写的所有方法都在执行相同的任务,所以我重构了它们,并且一个只包含一个格式方法的基decorator,因此上面的decorator继承自基decorator

我的副装饰师是这样的

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

现在我的问题是在子decorator中,相同的代码正在重复,所以我想重构我的代码,我应该如何重构我的代码?

您可以像在BaseDecorator类中一样重构它:

在你看来:

<%= @example.formatted_date("date1") %>
class ExampleDecorator < BaseDecorator
  def formatted_date(attribute_name)
    format_date(model, attribute_name)
  end
end
<%= @example.formatted_date("date1") %>