Sha256: a79bc36a3f658c9bb3a41ef4034b214ff7f515278832d3338df5e6623725746b

Contents?: true

Size: 1.61 KB

Versions: 4

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

require 'readymade/response'
require 'readymade/action'

module Readymade
  class Operation < Readymade::Action
    attr_reader :form, :record, :record_params

    private

    def build_form
      @form = form_class.new(record_params, record: record)
    end

    def form_valid?
      form.validate
    end

    def assign_attributes
      record.assign_attributes(record_params)
    end

    def record_valid?
      return true if record.errors.none? && record.valid?

      sync_errors_to_form && false
    end

    def save_record
      record.save
    end

    def response(status, *args)
      Response.new(status, *args)
    end

    def success(*args)
      response(:success, *args)
    end

    def validation_fail(status = :validation_fail, args = {})
      sync_errors_to_form
      response(status, args.merge!(record: record,
                                   record_params: record_params,
                                   form: form,
                                   errors: form.errors.messages))
    end

    def fail(status = :fail, args = {})
      sync_errors_to_form

      response(status, args.merge!(record: record,
                                   record_params: record_params,
                                   form: form,
                                   errors: form&.errors&.messages.presence || record&.errors&.messages))
    end

    def form_class
      raise 'Define your own form object class in your operation'
    end

    def sync_errors_to_form
      form.sync_errors(from: record, to: form)
    end

    def sync_errors_to_record
      form.sync_errors
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
readymade-0.1.3 lib/readymade/operation.rb
readymade-0.1.2 lib/readymade/operation.rb
readymade-0.1.1 lib/readymade/operation.rb
readymade-0.1.0 lib/readymade/operation.rb