Sha256: 20e55169bb53fd66a9ac63889b212ca3f328c3fe41b3c3cb50060fd2f0901f3c

Contents?: true

Size: 1.62 KB

Versions: 2

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

require 'eac_ruby_utils/patches/class/self_included_modules'
require 'eac_ruby_utils/patches/module/common_concern'

module EacRubyUtils
  # Support to abstract methods.
  #
  # Usage:
  #
  #   require 'eac_ruby_utils/acts_as_abstract'
  #
  #   class BaseClass
  #     include EacRubyUtils::ActsAsAbstract
  #
  #     abstract_methods :mymethod
  #   end
  #
  #   BaseClass.new.mymethod # raise "Abstract method: mymethod"
  #
  #   class SubClass
  #     def mymethod
  #       "Implemented"
  #     end
  #   end
  #
  #   SubClass.new.mymethod # return "Implemented"
  module ActsAsAbstract
    common_concern

    class << self
      def abstract?(a_class)
        a_class.self_included_modules.include?(::EacRubyUtils::ActsAsAbstract)
      end
    end

    module ClassMethods
      def abstract_methods(*methods_names)
        methods_names.each do |method_name|
          define_method method_name do
            raise_abstract_method(method_name)
          end
        end
      end
    end

    module InstanceMethods
      def respond_to_missing?(method_name, include_private = false)
        super || abstract_method?(method_name)
      end

      def method_missing(method_name, *arguments, &block)
        raise_abstract_method(method_name) if abstract_method?(method_name)

        super
      end

      def abstract_method?(method_name)
        self.class.abstract_methods.include?(method_name.to_sym)
      end

      def raise_abstract_method(method_name)
        raise ::NoMethodError, "Abstract method \"#{method_name}\" hit in \"#{self}\"" \
          " (Class: #{self.class})"
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
eac_ruby_utils-0.114.0 lib/eac_ruby_utils/acts_as_abstract.rb
eac_tools-0.64.0 sub/eac_ruby_utils/lib/eac_ruby_utils/acts_as_abstract.rb