Answers for "service object"

0

object service

# real use in controller
def destroy
  @result = YourService.call(first, second)
  if @result.success?
    #...
  else
    #...
  end
end
Posted by: Guest on October-23-2021
0

object service

class BaseService
  def self.call(*args)
    new(*args).call
  end
  
  def call
    raise NotImplementedError, "Missing instance method `call` of #{self.class} class"
  end
end

class RespondSevice
  attr_reader :payload, :errors
  def initialize(payload: nil, errors: [])
    @payload, @errors = payload, errors
  end
  
  def fail?
    errors.any?
  end
  
  def success?
    !fail?
  end
end
Posted by: Guest on October-23-2021
0

rails call a service

Service.call(args)
Posted by: Guest on November-30-2020
0

object service

class YourService < BaseService
  def initialize(first, second)
    @first, @second = first, second
  end

  def call
    #... process something
    return RespondService.new(errors: [{
      title: 'Cannot ...',
      detail: '...'
    }])
    #... process something
    RespondService.new(payload: payload)
  rescue ActiveRecord::RecordInvalid => e
    RespondService.new(errors: e.record.errors)
  end
  
  private
  # ... methods for call
end
Posted by: Guest on October-23-2021

Browse Popular Code Answers by Language