File: implement.rb

package info (click to toggle)
ruby-tins 1.32.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,248 kB
  • sloc: ruby: 6,659; makefile: 3
file content (40 lines) | stat: -rw-r--r-- 1,172 bytes parent folder | download
1
2
3
4
5
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
32
33
34
35
36
37
38
39
40
module Tins
  module Implement
    MESSAGES = {
      default:   'method %{method_name} not implemented in module %{module}',
      subclass:  'method %{method_name} has to be implemented in '\
        'subclasses of %{module}',
      submodule: 'method %{method_name} has to be implemented in '\
        'submodules of %{module}',
    }

    def implement(method_name, msg = :default)
      method_name.nil? and return
      case msg
      when ::Symbol
        msg = MESSAGES.fetch(msg)
      when ::Hash
        return implement method_name, msg.fetch(:in)
      end
      display_method_name = method_name
      if m = instance_method(method_name) rescue nil
        m.extend Tins::MethodDescription
        display_method_name = m.description(style: :name)
      end
      begin
        msg = msg % { method_name: display_method_name, module: self }
      rescue KeyError
      end
      define_method(method_name) do |*|
        raise ::NotImplementedError, msg
      end
    end

    def implement_in_submodule(method_name)
      implement method_name,
        'method %{method_name} has to be implemented in submodules of'\
        ' %{module}'
    end
  end
end