Class: AlterOut

Inherits:
Object
  • Object
show all
Defined in:
lib/alterout.rb

Overview

Decorator to modify method outputs.

For more information read README file.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2020-2023 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(origin, methods = {}) ⇒ AlterOut

Returns a new instance of AlterOut.



34
35
36
37
# File 'lib/alterout.rb', line 34

def initialize(origin, methods = {})
  @origin = origin
  @methods = methods
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/alterout.rb', line 48

def method_missing(*args)
  method = args[0]
  raise "Method #{method} is absent in #{@origin}" unless @origin.respond_to?(method)
  out =
    if block_given?
      @origin.__send__(*args) do |*a|
        yield(*a)
      end
    else
      @origin.__send__(*args)
    end
  out = @methods[method].call(out) if @methods.key?(method)
  out
end

Instance Method Details

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/alterout.rb', line 63

def respond_to?(method, include_private = false)
  @origin.respond_to?(method, include_private) || @methods.key?(method)
end

#respond_to_missing?(_method, _include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/alterout.rb', line 67

def respond_to_missing?(_method, _include_private = false)
  true
end

#to_json(options = nil) ⇒ Object



43
44
45
46
# File 'lib/alterout.rb', line 43

def to_json(options = nil)
  return @origin.to_a.to_json(options) if @origin.is_a?(Array)
  method_missing(:to_json, options)
end

#to_sObject



39
40
41
# File 'lib/alterout.rb', line 39

def to_s
  method_missing(:to_s)
end