Class: Module

Inherits:
Object show all
Defined in:
lib/ruby/module.rb

Instance Method Summary collapse

Instance Method Details

#abstract(name, *params) ⇒ void

This method returns an undefined value.

Creates an abstract method

Examples:

class Collection
  abstract :size
  abstract :add, :args => %w(item)
end


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ruby/module.rb', line 12

def abstract(name, *params)
  if params.last.is_a?(Hash)
    # abstract :method, :args => %w(a b c)
    params = params.last[:args]
  end

  file, line, = Stupidedi.caller

  if params.empty?
    class_eval(<<-RUBY, file, line.to_i - 1)
      def #{name}(*args)
        raise NoMethodError,
          "method \#{self.class.name}.#{name} is abstract"
      end
    RUBY
  else
    class_eval(<<-RUBY, file, line.to_i - 1)
      def #{name}(*args)
        raise NoMethodError,
          "method \#{self.class.name}.#{name}(#{params.join(', ')}) is abstract"
      end
    RUBY
  end
end

#delegate(*params) ⇒ void

This method returns an undefined value.

Creates a method (or methods) that delegates messages to an instance variable or another instance method.

Examples:

class WrappedCollection
  delegate :size, :add, :to => :@wrapped

  def initialize(wrapped)
    @wrapped = wrapped
  end
end


50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ruby/module.rb', line 50

def delegate(*params)
  unless params.last.is_a?(Hash)
    raise ArgumentError,
      "last argument must be :to => ..."
  end

  methods = params.init
  target  = params.last.fetch(:to) or
    raise ArgumentError,
      ":to => ... cannot be nil"

  file, line, = Stupidedi.caller

  for m in methods
    if m.to_s =~ /=$/
      class_eval(<<-RUBY, file, line.to_i - 1)
        def #{m}(value)
          #{target}.#{m}(value)
        end
      RUBY
    else
      class_eval(<<-RUBY, file, line.to_i - 1)
        def #{m}(*args, &block)
          #{target}.#{m}(*args, &block)
        end
      RUBY
    end
  end
end