Clean way of initializing service objects in ruby

April 6, 2018

# 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
Clean way of initializing service objects in ruby - April 6, 2018 - {"name"=>"Stanislav Knyazev", "email"=>"extazystas@gmail.com"}