Clean way of initializing service objects in ruby

# service object class
class FancyObject
  attr_reader :entity

  def self.perform(params)
    new(params).perform
  end

  def perform
    ApplicationRecord.transaction do
      # entity processing logic here

      entity.save
      entity
    end
  end

  private

  def initialize(params)
    @entity   = Entity.new(params)
  end
end

# controller:
@entity = FancyObject.perform(entity_params)

if @entity.valid?
  #...
end

Поделиться с друзьями

Френдинг

 

Comments

No comments so far.

Leave a Reply

 
(will not be published)
 
 
Comment