私有服务对象方法(Ruby + Rails)



我有一个PaymentManager服务:

/payment_manager/
- online_payment_creator.rb
- manual_payment_creator.rb
- payment_splitter.rb

3 项服务的代码:

module PaymentManager
class ManualPaymentCreator < ApplicationService
def call
# do stuff in transaction
PaymentSplitter.call(a, b, c)
end
end
end
module PaymentManager
class OnlinePaymentCreator < ApplicationService
# do stuff in transaction
PaymentSplitter.call(a2, b2, c2)
end
end
module PaymentManager
class PaymentSplitter < ApplicationService
def call(x, y, z)
# do very dangerous stuff
end
end
end

因此,PaymentSplitter实质上是将付款拆分到多个发票中,并且只能在其他 2 个服务中的任何一个中完成,但绝不应单独调用(从控制器或在控制台等中调用(。

我通常会在ManualPaymentCreator内部创建一个private方法,但由于两个服务都需要它,我不知道该怎么做,因为我不能在没有重复的情况下使用简单的私有实例方法。

也许您正在寻找继承和受保护的方法

class Foo < ApplicationService
def public_method
end
protected
#everything after here is private to this class and its descendants
def some_method_to_be_shared_with_descendants
#I am only accessible from this class and from descendants of this class
...
end
private
#Everything after here is private to this class only
def some_private_methods_that_are_only_accessible_from_this_class
end
...
end

然后像这样的后代类

class Bar < Foo
def do_something
# can access protected methods from Foo class here as native methods
some_res = some_method_to_be_shared_here
# do something with some_res
end
end

因此,您应该从PaymentSplitter下降其他2个类,并将共享方法设置为受保护

也许模块中包含的私有类可能会更好,例如。

module PaymentSplitting
def self.included(klass)
raise 'Error' unless klass.in?([ManualPaymentCreator, OnlinePaymentCreator])
end
class PaymentSplitter
end
private_constant :PaymentSplitter
end

这应该允许您在任何包含PaymentSplitting的类中自由引用PaymentSplitter,并且您只能在ManualPaymentCreatorOnlinePaymentCreator中包含PaymentSplitting。引用PaymentSplitting::PaymentSplitter将引发NameError: private constant异常。

最新更新