Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#decoor(origin, attrs = {}) ⇒ Object

A function that turns decorates an object.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
# File 'lib/decoor.rb', line 28

def decoor(origin, attrs = {}, &)
  if block_given?
    c = Class.new do
      def initialize(origin, attrs)
        @origin = origin
        # rubocop:disable Style/HashEachMethods
        # rubocop:disable Lint/UnusedBlockArgument
        attrs.each do |k, v|
          instance_eval("@#{k} = v", __FILE__, __LINE__) # @foo = v
        end
        # rubocop:enable Style/HashEachMethods
        # rubocop:enable Lint/UnusedBlockArgument
      end

      def method_missing(*args)
        @origin.__send__(*args) do |*a|
          yield(*a) if block_given?
        end
      end

      def respond_to?(_mtd, _inc = false)
        true
      end

      def respond_to_missing?(_mtd, _inc = false)
        true
      end
    end
    c.class_eval(&)
    c.new(origin, attrs)
  else
    class_eval("def __get_origin__; @#{origin}; end", __FILE__, __LINE__) # def _get; @name; end
    class_eval do
      def method_missing(*args)
        o = __get_origin__
        o.send(*args) do |*a|
          yield(*a) if block_given?
        end
      end

      def respond_to?(_mtd, _inc = false)
        true
      end

      def respond_to_missing?(_mtd, _inc = false)
        true
      end
    end
  end
end