我想用一个装饰器模式来装饰我的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和View我正在通过以下方式调用
= @example.date1
= @example.date2
= @example.date3所以在上面的装饰器中编写的所有方法都在做相同的任务,所以我重构了它和一个只包含一个格式方法的基装饰器,所以上面的装饰器继承了基装饰器
喜欢
class BaseDecorator < Draper::Decorator
def format_date(model_name, attribute_name)
model_name.attributes[attriburte_name].strftime("%d-%m-%Y")
end
end我的子装饰器看起来像这样
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所以现在我的问题是,在子装饰器中,相同的代码正在重复,所以我想重构我的代码,我应该如何重构我的代码?
发布于 2015-04-16 08:56:54
您可以类似于在BaseDecorator类中所做的那样进行重构:
class ExampleDecorator < BaseDecorator
def formatted_date(attribute_name)
format_date(model, attribute_name)
end
end在你看来:
<%= @example.formatted_date("date1") %>https://stackoverflow.com/questions/27442971
复制相似问题