Sha256: a61adc911295d9cd46c459a98f22ceaf7d5f5bf3682a39e3e8dc32a92888bd7f

Contents?: true

Size: 865 Bytes

Versions: 9

Compression:

Stored size: 865 Bytes

Contents

class AttrExtras::AttrImplement
  def initialize(klass, names)
    @klass, @names = klass, names.dup
  end

  def apply
    arg_names = @names.last.is_a?(Array) ? @names.pop : []
    expected_arity = arg_names.length

    # Make available within the block.
    names = @names

    mod = Module.new do
      define_method :method_missing do |name, *args|
        if names.include?(name)
          provided_arity = args.length

          if provided_arity != expected_arity
            raise ArgumentError, "wrong number of arguments (#{provided_arity} for #{expected_arity})"
          end

          raise AttrExtras::MethodNotImplementedError, "Implement a '#{name}(#{arg_names.join(", ")})' method"
        else
          super(name, *args)
        end
      end
    end

    # include is private in Ruby 2.0 and earlier.
    @klass.send(:include, mod)
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
attr_extras-6.2.2 lib/attr_extras/attr_implement.rb
attr_extras-6.2.1 lib/attr_extras/attr_implement.rb
attr_extras-6.2.0 lib/attr_extras/attr_implement.rb
attr_extras-6.1.0 lib/attr_extras/attr_implement.rb
attr_extras-5.2.0 lib/attr_extras/attr_implement.rb
attr_extras-5.1.0 lib/attr_extras/attr_implement.rb
attr_extras-5.0.0 lib/attr_extras/attr_implement.rb
attr_extras-4.6.0 lib/attr_extras/attr_implement.rb
attr_extras-4.5.0 lib/attr_extras/attr_implement.rb