Top Level Namespace

Instance Method Summary collapse

Instance Method Details

#others(attrs = {}, &block) ⇒ Object

A function that catches all undeclared methods.

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/others.rb', line 28

def others(attrs = {}, &block)
  if is_a?(Class)
    class_exec(block) do |b|
      # rubocop:disable Style/ClassVars
      class_variable_set(:@@__others_block__, b)
      # rubocop:enable Style/ClassVars

      def method_missing(*args)
        raise 'Block cannot be provided' if block_given?
        b = self.class.class_variable_get(:@@__others_block__)
        instance_exec(*args, &b)
      end

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

      def respond_to_missing?(_mtd, _inc = false)
        true
      end
    end
  else
    c = Class.new do
      def initialize(attrs, &block)
        # 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
        @block = block
      end

      def method_missing(*args)
        raise 'Block cannot be provided' if block_given?
        instance_exec(*args, &@block)
      end

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

      def respond_to_missing?(_mtd, _inc = false)
        true
      end
    end
    c.new(attrs, &block)
  end
end