编写活动装饰器DRY

tru*_*gnm 1 ruby datetime rubygems ruby-on-rails decorator

我正在使用ActiveDecorator:https : //github.com/amatsuda/active_decorator

在编写my时UserDecorator,我发现它有很多重叠之处。只是装饰,datetime但我不得不重复写很多装饰器。

# frozen_string_literal: true

module UserDecorator
  def created_at_datetime
    created_at&.strftime '%Y/%m/%d %H:%M:%S'
  end

  def confirmed_at_datetime
    confirmed_at&.strftime '%Y/%m/%d %H:%M:%S'
  end

  def locked_at_datetime
    locked_at&.strftime '%Y/%m/%d %H:%M:%S'
  end

  def current_sign_in_at_datetime
    current_sign_in_at&.strftime '%Y/%m/%d %H:%M:%S'
  end

  def last_sign_in_at_datetime
    last_sign_in_at&.strftime '%Y/%m/%d %H:%M:%S'
  end
end
Run Code Online (Sandbox Code Playgroud)

猜猜怎么着,我的AdminDecorator领域完全一样。我是否必须将所有这些都再次复制到AdminDecorator?有什么建议吗?

参考:https : //github.com/amatsuda/active_decorator/issues/104

jvi*_*ian 5

我不使用active_decorator,但是我认为我很想创建一个DatetimeDecorator,例如:

module DatetimeDecorator

  %i(
    created_at
    confirmed_at
    locked_at
    current_sign_in_at
    last_sign_in_at
  ).each do |attr_sym|
    define_method("#{attr_sym}_datetime") do 
      send(attr_sym)&.strftime '%Y/%m/%m %H:%M:%S'
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

无论何时包含此模块,都将获得先前定义的五个方法,UserDecorator每个方法都使用相同的格式代码。

现在,要包括该模块,请使用included钩子。就像是:

module UserDecorator

  self.included(base)
    base.class_eval do 
      include DatetimeDecorator
    end
  end

end

module AdminDecorator

  self.included(base)
    base.class_eval do 
      include DatetimeDecorator
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

现在,您UserDecorator和您AdminDecorator都拥有先前在中定义的五个方法UserDecorator

这未经测试,因此您可能需要摆弄一下。