File: decorators.rb

package info (click to toggle)
ruby-contracts 0.17-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 624 kB
  • sloc: ruby: 3,805; makefile: 4; sh: 2
file content (50 lines) | stat: -rw-r--r-- 1,267 bytes parent folder | download | duplicates (2)
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
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true

module Contracts
  module MethodDecorators
    def self.extended(klass)
      Engine.apply(klass)
    end

    def inherited(subclass)
      Engine.fetch_from(subclass).set_eigenclass_owner
      super
    end

    def method_added(name)
      MethodHandler.new(name, false, self).handle
      super
    end

    def singleton_method_added(name)
      MethodHandler.new(name, true, self).handle
      super
    end
  end

  class Decorator
    # an attr_accessor for a class variable:
    class << self; attr_accessor :decorators; end

    def self.inherited(klass)
      super
      name = klass.name.gsub(/^./) { |m| m.downcase }

      return if name =~ /^[^A-Za-z_]/ || name =~ /[^0-9A-Za-z_]/

      # the file and line parameters set the text for error messages
      # make a new method that is the name of your decorator.
      # that method accepts random args and a block.
      # inside, `decorate` is called with those params.
      MethodDecorators.module_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
        def #{klass}(*args, &blk)
          ::Contracts::Engine.fetch_from(self).decorate(#{klass}, *args, &blk)
        end
      RUBY_EVAL
    end

    def initialize(klass, method)
      @method = method
    end
  end
end