Sha256: ec4c1065d12c855934516cab7e090cf5bcf16b95da7912b211d6fb6a5f18785b

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

module RespondForHelper
  class Respond
    def initialize(controller, item, options)
      @controller = controller
      @item = item
      @options = options

      unless @options.key?(:success)
        @options[:success] = Array(item).all? { |item| item.errors.blank? }
      end

      @callbacks = {}
    end

    def success?
      @options[:success]
    end

    def before_success(&block)
      @callbacks[:before_success] ||= []
      @callbacks[:before_success] << block
    end

    def before_failure(&block)
      @callbacks[:before_failure] ||= []
      @callbacks[:before_failure] << block
    end

    def after_success(&block)
      @callbacks[:after_success] ||= []
      @callbacks[:after_success] << block
    end

    def after_failure(&block)
      @callbacks[:after_failure] ||= []
      @callbacks[:after_failure] << block
    end

    def run_before_callbacks
      if success?
        run_callbacks_for(:before_success)
      else
        run_callbacks_for(:before_failure)
      end
    end

    def run_after_callbacks
      if success?
        run_callbacks_for(:after_success)
      else
        run_callbacks_for(:after_failure)
      end
    end

    def run_callbacks_for(name)
      if @callbacks[name]
        @callbacks[name].each do |callback|
          callback.call
        end
      end
    end

    def formatters
      Lookups::Format.new(@controller, @options).call.map do |_, klass|
        klass.new(@controller, @item, @options)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
respond_for_helper-1.1.1 lib/respond_for_helper/respond.rb
respond_for_helper-1.1.0 lib/respond_for_helper/respond.rb