Class: Tacky
- Inherits:
-
Object
- Object
- Tacky
- Defined in:
- lib/tacky.rb
Overview
Tacky is a simple decorator of an existing object that makes all 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-2023 Yegor Bugayenko
- License
-
MIT
Constant Summary collapse
- STOP =
Deep nesting will stop at these classes.
[ Numeric, NilClass, TrueClass, FalseClass, Array, Hash, Time, String ].freeze
Instance Method Summary collapse
-
#initialize(origin, deep: true) ⇒ Tacky
constructor
A new instance of Tacky.
- #method_missing(*args) ⇒ Object
- #respond_to?(method, include_private = false) ⇒ Boolean
- #respond_to_missing?(_method, _include_private = false) ⇒ Boolean
Constructor Details
#initialize(origin, deep: true) ⇒ Tacky
Returns a new instance of Tacky.
46 47 48 49 50 51 |
# File 'lib/tacky.rb', line 46 def initialize(origin, deep: true) @origin = origin @cache = {} @deep = deep @mutex = Mutex.new end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(*args) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/tacky.rb', line 53 def method_missing(*args) @mutex.synchronize do unless @cache.key?(args) @cache[args] = @origin.__send__(*args) do |*a| yield(*a) if block_given? end @cache[args] = Tacky.new(@cache[args], deep: @deep) if @deep && STOP.none? { |t| @cache[args].is_a?(t) } end @cache[args] end end |
Instance Method Details
#respond_to?(method, include_private = false) ⇒ Boolean
65 66 67 |
# File 'lib/tacky.rb', line 65 def respond_to?(method, include_private = false) @origin.respond_to?(method, include_private) end |
#respond_to_missing?(_method, _include_private = false) ⇒ Boolean
69 70 71 |
# File 'lib/tacky.rb', line 69 def respond_to_missing?(_method, _include_private = false) true end |