Class: AttrExtras::AttrImplement

Inherits:
Object
  • Object
show all
Defined in:
lib/attr_extras/attr_implement.rb

Instance Method Summary collapse

Constructor Details

#initialize(klass, names) ⇒ AttrImplement

Returns a new instance of AttrImplement.



2
3
4
# File 'lib/attr_extras/attr_implement.rb', line 2

def initialize(klass, names)
  @klass, @names = klass, names.dup
end

Instance Method Details

#applyObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/attr_extras/attr_implement.rb', line 6

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