Sha256: 359b2363429f0f34449bf3ee8fa22efd7a4a121b4c39defb61cfdfabf8d7f73b

Contents?: true

Size: 1.74 KB

Versions: 12

Compression:

Stored size: 1.74 KB

Contents

require 'virtus'
module SuperProcess
  class Core
    include ActiveModel::Validations
    include ActiveSupport::Callbacks
    include Virtus.model

    ValidError = Class.new(StandardError)

    define_callbacks :validations, :task

    def self.before_call(method_name)
      set_callback :validations, :before, method_name
    end

    def self.after_call(method_name)
      set_callback :validations, :after, method_name
    end

    def self.before_task(method_name)
      set_callback :task, :before, method_name
    end

    def self.after_task(method_name)
      set_callback :task, :after, method_name
    end

    def self.init(model_name, &block)
      attr_accessor model_name

      class_eval(&block) if block_given?

      define_method :initialize do |model|
        self.send("#{model_name}=", model)
      end
    end

    def self.callable(&block)
      define_method :call! do |params={}|
        params.each do |attr, value|
          public_send("#{attr}=", value) if respond_to?("#{attr}=")
        end
        run_callbacks :validations do
          raise ValidError, "Validation Error" if valid? == false

          run_callbacks :task do
            instance_eval(&block)
          end
        end
      end

      define_method :call do |params={}|
        begin
          @result = call!(params)
          true
        rescue ValidError
          false
        end
      end
    end

    def result
      @result
    end

    def error_messages
      if errors.messages.values.present?
        errors.messages.values.first.first
      else
        ""
      end
    end

    def self.method_missing(m, *args, &block)
      if block_given?
        new.public_send(m, *args, &block)
      else
        new.public_send(m, *args)
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
super_tools-2.1.0 lib/super_process/core.rb
super_tools-0.0.26 lib/super_process/core.rb
super_tools-0.0.25 lib/super_process/core.rb
super_tools-0.0.21 lib/super_process/core.rb
super_tools-0.0.20 lib/super_process/core.rb
super_tools-0.0.17 lib/super_process/core.rb
super_tools-0.0.15 lib/super_process/core.rb
super_tools-0.0.14 lib/super_process/core.rb
super_tools-0.0.13 lib/super_process/core.rb
super_tools-0.0.12 lib/super_process/core.rb
super_tools-0.0.11 lib/super_process/core.rb
super_tools-0.0.10 lib/super_process/core.rb