Sha256: 702b6f854da91063ebc9e18e2589695845065d03977548aa1cd8f6dc3ea97f29

Contents?: true

Size: 1.59 KB

Versions: 21

Compression:

Stored size: 1.59 KB

Contents

# frozen_string_literal: true

require 'colorized_string'
require 'eac_ruby_utils/listable'

module Avm
  class Result < ::SimpleDelegator
    include ::EacRubyUtils::Listable

    lists.add_string :type, :success, :error, :neutral

    lists.type.values.each do |type|
      class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def self.#{type}(value)
          new(value, TYPE_#{type.upcase})
        end
      RUBY_EVAL
    end

    TYPE_SUCCESS_COLOR = 'green'
    TYPE_ERROR_COLOR = 'red'
    TYPE_NEUTRAL_COLOR = 'light_black'

    class << self
      def success_or_error(value, success)
        new(value, success ? ::Avm::Result::TYPE_SUCCESS : ::Avm::Result::TYPE_ERROR)
      end
    end

    attr_reader :type

    def initialize(value, type)
      super(value)
      validate_type(type)
      @type = type
    end

    def label
      label_fg
    end

    def label_fg
      ColorizedString.new(to_s).send(type_color)
    end

    def label_bg
      ColorizedString.new(to_s).light_white.send("on_#{type_color}")
    end

    def type_color
      self.class.const_get("type_#{type}_color".upcase)
    end

    lists.type.values.each do |type|
      class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def #{type}?
          @type == '#{type}'
        end
      RUBY_EVAL
    end

    private

    def validate_type(type)
      return if self.class.lists.type.values.include?(type)

      raise "Tipo desconhecido: \"#{type}\" (VĂ¡lido: #{self.class.lists.type.values.join(', ')})"
    end

    class Error < StandardError
      def to_result
        ::Avm::Result.error(message)
      end
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
avm-tools-0.34.0 lib/avm/result.rb
avm-tools-0.33.1 lib/avm/result.rb
avm-tools-0.33.0 lib/avm/result.rb
avm-tools-0.32.0 lib/avm/result.rb
avm-tools-0.31.0 lib/avm/result.rb
avm-tools-0.30.0 lib/avm/result.rb
avm-tools-0.28.0 lib/avm/result.rb
avm-tools-0.27.0 lib/avm/result.rb
avm-tools-0.26.0 lib/avm/result.rb
avm-tools-0.25.0 lib/avm/result.rb
avm-tools-0.24.0 lib/avm/result.rb
avm-tools-0.23.0 lib/avm/result.rb
avm-tools-0.22.0 lib/avm/result.rb
avm-tools-0.21.0 lib/avm/result.rb
avm-tools-0.20.0 lib/avm/result.rb
avm-tools-0.19.0 lib/avm/result.rb
avm-tools-0.18.0 lib/avm/result.rb
avm-tools-0.17.0 lib/avm/result.rb
avm-tools-0.16.0 lib/avm/result.rb
avm-tools-0.15.1 lib/avm/result.rb