Class: Veil

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

Overview

Veil is a simple decorator of an existing object that makes some of its methods cache all values and calculate them only once.

For more information read README file.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2020 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Veil.



35
36
37
38
39
# File 'lib/veil.rb', line 35

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/veil.rb', line 50

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

Instance Method Details

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

Returns:

  • (Boolean)


69
70
71
# File 'lib/veil.rb', line 69

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

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

Returns:

  • (Boolean)


73
74
75
# File 'lib/veil.rb', line 73

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

#to_json(options = nil) ⇒ Object



45
46
47
48
# File 'lib/veil.rb', line 45

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



41
42
43
# File 'lib/veil.rb', line 41

def to_s
  method_missing(:to_s)
end