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-2025 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
27 28 29 30 31 32 |
# File 'lib/tacky.rb', line 27 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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/tacky.rb', line 34 def method_missing(*args) @mutex.synchronize do key = args.dup mtd = args.shift unless @cache.key?(key) params = @origin.method(mtd).parameters @cache[key] = if params.any? { |p| p[0] == :keyreq } @origin.__send__(mtd, *args[0...-1], **args.last) do |*a| yield(*a) if block_given? end else @origin.__send__(mtd, *args) do |*a| yield(*a) if block_given? end end @cache[key] = Tacky.new(@cache[key], deep: @deep) if @deep && STOP.none? { |t| @cache[key].is_a?(t) } end @cache[key] end end |
Instance Method Details
#respond_to?(method, include_private = false) ⇒ Boolean
56 57 58 |
# File 'lib/tacky.rb', line 56 def respond_to?(method, include_private = false) @origin.respond_to?(method, include_private) end |
#respond_to_missing?(_method, _include_private = false) ⇒ Boolean
60 61 62 |
# File 'lib/tacky.rb', line 60 def respond_to_missing?(_method, _include_private = false) true end |