Sha256: fd24e4f565ecdac41acbf58a302c09ffba5aeb08b6e3caf130ceec715f24a036

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

module Domain
  module Reuse

    def self.new(reuse_domain, predicate = nil, &bl)
      ImplDomain.new [ Methods, class_module(predicate || bl) ],
                     [ instance_module(reuse_domain) ]
    end

    def self.class_module(predicate)
      Module.new{ define_method(:predicate){ predicate } }
    end

    def self.instance_module(reuse_domain)
      Module.new{
        define_method(:initialize) do |arg|
          unless reuse_domain===arg
            raise ArgumentError, "#{reuse_domain} expected, got `#{arg.inspect}`"
          end
          if self.class.predicate && !self.class.predicate.call(arg)
            raise ArgumentError, "Invalid value `#{arg.inspect}` for `#{self}`"
          end
          @reused_instance = arg
        end
        define_method(:reused_instance) do
          @reused_instance
        end
        protected :reused_instance
        include Equalizer.new(:reused_instance)
      }
    end

    module Methods

      def reuse(*methods)
        methods.each do |m|
          define_method(m) do |*args, &bl|
            reused_instance.send(m, *args, &bl)
          end
        end
      end

      def recoat(*methods)
        methods.each do |m|
          define_method(m) do |*args, &bl|
            self.class.new reused_instance.send(m, *args, &bl)
          end
        end
      end

    end # module Methods

  end # module Reuse
end # module Domain

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
domain-1.0.0.rc1 lib/domain/factory/reuse.rb