在我的应用程序中,我有两个管理持久性的服务对象:
class UpdateProductService
<...>
def update_product
product_in_db.attributes = product_params
product_in_db.save! if product_in_db.changed?
end
<...>
end
另一个:
class CreateProductService
<...>
def create_product
self.product = account.products.create!(product_params)
end
<...>
end
这些对象都使用属性 'product_params' 的哈希和其他一些属性的哈希。喜欢这个:
def product_params
{
archived: product.archived,
available: product.available,
category_id: product.category_id,
short_description: product.short_description,
description: product.description,
title: product.title,
}
end
这些哈希现在存储在两个服务中,并且相互复制。问题是:我可以在哪里放置这个和其他属性哈希(在哪个文件中,在应用程序树中的位置),以使用一些"产品"作为参数从我的服务对象调用它们。
这
对我来说似乎是一个问题。把它放在app/services/concerns
(或app/service_objects/concerns
,无论你的服务在哪里)。
module Concerns
module WithProductParams
extend ActiveSupport::Concern
def product_params
{
archived: product.archived,
available: product.available,
category_id: product.category_id,
short_description: product.short_description,
description: product.description,
title: product.title,
}
end
end
end
然后像这样使用它:
class CreateProductService
include Concerns::WithProductParams