SuccessfulResult=Struct.new:payloaddodefself.create(payload:nil)fail'payload must have to respond_to method "as_json".'unlesspayload.respond_to?:as_jsonnew(payload)enddefsuccess?trueenddefas_json(*){success:true,payload:payload.as_json}enddeferrornilendendFailedResult=Struct.new:errordodefself.create(error:ServiceObjectError.new)new(error)enddefsuccess?falseenddefas_json(*){success:false,error:error.as_json}enddefpayloadnilendend

實驗性範例，目前僅供參考（如有問題，不負責任）

建立一個ActsAsServiceObjectmodule，當做該介面的角色

moduleActsAsServiceObjectSuccessfulResult=Struct.new:payloaddodefself.create(payload:nil)fail'payload must have to respond_to method "as_json".'unlesspayload.respond_to?:as_jsonnew(payload)enddefsuccess?trueenddefas_json(*){success:true,payload:payload.as_json}enddeferrornilendendFailedResult=Struct.new:errordodefself.create(error:ServiceObjectError.new)new(error)enddefsuccess?falseenddefas_json(*){success:false,error:error.as_json}enddefpayloadnilendendclassServiceObjectError<StandardErrorattr_reader:caused_bydefinitialize(message=nil,caused_by:nil)super(message)@caused_by=caused_byendalias_method:original_message,:messagedefcodeself.class.nameenddefas_json(*){message:message,code:code}endend# 唯一的對外公開方法，統一都傳hash當做參數，基本上include該module不需特別覆寫此方法 defexecute(args={})SuccessfulResult.createpayload:process(args)rescueServiceObjectError=>eFailedResult.createerror:eendprivate# include該module的類別，唯一需要自己實作的方法，預設都需一個args型態為hash的參數# 而此方法的最後回傳值會被當做SuccessfulResult物件的payload# 而當方法裡有任何繼承ServiceObjectError的例外發生都會被捕捉成FailedObjectdefprocess(args={})fail'my son will take care of you'endend