memo_ttl 0.9.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.rspec_status +18 -0
- data/.rubocop.yml +14 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE +21 -0
- data/LICENSE.txt +21 -0
- data/README.md +104 -0
- data/Rakefile +12 -0
- data/lib/memo_ttl/cache.rb +126 -0
- data/lib/memo_ttl/class_methods.rb +45 -0
- data/lib/memo_ttl/instance_methods.rb +120 -0
- data/lib/memo_ttl/version.rb +5 -0
- data/lib/memo_ttl.rb +21 -0
- data/sig/memo_ttl.rbs +4 -0
- metadata +59 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 6ba7210c4b45af27a52d7a6b86053ca2bdfc97929d2968803af7e15abfaa73c0
|
4
|
+
data.tar.gz: 4306221408051fdd1308972bb553d4577d2c9ae41c28e47e1526ce391fb3f1dc
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 236d78b10240f22e4d77773103aa38d02cc5ebe647bbb81166189df066bf28b3418a2ef5fb6720bee38336918f4b44e9f6cd4c63bcb7c445940d6d10ee1948b5
|
7
|
+
data.tar.gz: 3bab4d3842a2ee8b22476080360a3c003e00dacbc95bcce88aa29e3463cc5f8d85eb41725742184f455396faca513e774c1224418799eb075e09ab50be40f01e
|
data/.rspec
ADDED
data/.rspec_status
ADDED
@@ -0,0 +1,18 @@
|
|
1
|
+
example_id | status | run_time |
|
2
|
+
------------------------------ | ------ | --------------- |
|
3
|
+
./spec/cache_spec.rb[1:1] | passed | 0.00056 seconds |
|
4
|
+
./spec/cache_spec.rb[1:2] | passed | 0.00072 seconds |
|
5
|
+
./spec/cache_spec.rb[1:3] | passed | 0.00006 seconds |
|
6
|
+
./spec/cache_spec.rb[1:4] | passed | 0.00007 seconds |
|
7
|
+
./spec/cache_spec.rb[1:5] | passed | 0.00007 seconds |
|
8
|
+
./spec/cache_spec.rb[1:6] | passed | 0.00014 seconds |
|
9
|
+
./spec/cache_spec.rb[1:7] | passed | 0.00009 seconds |
|
10
|
+
./spec/memo_ttl_spec.rb[1:1:1] | passed | 0.00317 seconds |
|
11
|
+
./spec/memo_ttl_spec.rb[1:1:2] | passed | 0.00008 seconds |
|
12
|
+
./spec/memo_ttl_spec.rb[1:1:3] | passed | 0.00008 seconds |
|
13
|
+
./spec/memo_ttl_spec.rb[1:2:1] | passed | 0.0001 seconds |
|
14
|
+
./spec/memo_ttl_spec.rb[1:2:2] | passed | 0.00009 seconds |
|
15
|
+
./spec/memo_ttl_spec.rb[1:3:1] | passed | 0.00012 seconds |
|
16
|
+
./spec/memo_ttl_spec.rb[1:3:2] | passed | 0.00008 seconds |
|
17
|
+
./spec/memo_ttl_spec.rb[1:3:3] | passed | 0.0001 seconds |
|
18
|
+
./spec/memo_ttl_spec.rb[1:3:4] | passed | 0.00029 seconds |
|
data/.rubocop.yml
ADDED
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Mishal Zaman
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 Mishal
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,104 @@
|
|
1
|
+
# MemoTTL
|
2
|
+
|
3
|
+
**MemoTTL** is a thread-safe memoization utility for Ruby that supports TTL (Time-To-Live) and LRU (Least Recently Used) eviction. It's designed for scenarios where memoized values should expire after a period and memory usage must be constrained.
|
4
|
+
|
5
|
+
## Features
|
6
|
+
|
7
|
+
- Memoize method results with expiration (TTL)
|
8
|
+
- Built-in LRU eviction to limit memory usage
|
9
|
+
- Thread-safe with Monitor
|
10
|
+
- Easy integration via `include MemoTTL`
|
11
|
+
|
12
|
+
## Installation
|
13
|
+
|
14
|
+
Add this line to your application's Gemfile:
|
15
|
+
|
16
|
+
```ruby
|
17
|
+
gem "memo_ttl"
|
18
|
+
```
|
19
|
+
|
20
|
+
Afterwards:
|
21
|
+
|
22
|
+
```ruby
|
23
|
+
bundle install
|
24
|
+
```
|
25
|
+
|
26
|
+
## Usage
|
27
|
+
|
28
|
+
```ruby
|
29
|
+
require "memo_ttl"
|
30
|
+
|
31
|
+
class Calculator
|
32
|
+
include MemoTTL
|
33
|
+
|
34
|
+
def a_method_that_does_something(x)
|
35
|
+
sleep(2) # simulate slow process
|
36
|
+
x * 2
|
37
|
+
end
|
38
|
+
|
39
|
+
# use at the bottom due to Ruby's top-down evalation of methods
|
40
|
+
memoize :a_method_that_does_something, ttl: 60, max_size: 100
|
41
|
+
end
|
42
|
+
|
43
|
+
calc = Calculator.new
|
44
|
+
calc.a_method_that_does_something(5) # takes 2 seconds
|
45
|
+
calc.a_method_that_does_something(5) # returns instantly from cache
|
46
|
+
```
|
47
|
+
|
48
|
+
To clear the cache:
|
49
|
+
|
50
|
+
```ruby
|
51
|
+
calc.clear_memoized_method(:a_method_that_does_something)
|
52
|
+
calc.clear_all_memoized_methods
|
53
|
+
calc.cleanup_memoized_methods
|
54
|
+
```
|
55
|
+
|
56
|
+
### Rails Example
|
57
|
+
|
58
|
+
```ruby
|
59
|
+
require 'memo_ttl'
|
60
|
+
|
61
|
+
class TestController < ApplicationController
|
62
|
+
include MemoTTL
|
63
|
+
|
64
|
+
def index
|
65
|
+
result1 = test_method(1, 2)
|
66
|
+
result2 = test_method(1, 2)
|
67
|
+
result3 = test_method(5, 2)
|
68
|
+
result4 = test_method(1, 2)
|
69
|
+
result5 = test_method(1, 2)
|
70
|
+
result6 = test_method(3, 4)
|
71
|
+
|
72
|
+
render plain: <<~TEXT
|
73
|
+
Result 1: #{result1}
|
74
|
+
Result 2: #{result2}
|
75
|
+
Result 3: #{result3}
|
76
|
+
Result 4: #{result4}
|
77
|
+
Result 5: #{result5}
|
78
|
+
Result 6: #{result6}
|
79
|
+
TEXT
|
80
|
+
end
|
81
|
+
|
82
|
+
def test_method(x, y)
|
83
|
+
puts "Calling test_method(#{x}, #{y})"
|
84
|
+
x + y
|
85
|
+
end
|
86
|
+
|
87
|
+
def clean_up
|
88
|
+
clear_memoized_method(:test_method)
|
89
|
+
clear_all_memoized_methods
|
90
|
+
cleanup_memoized_methods
|
91
|
+
end
|
92
|
+
|
93
|
+
memoize :test_method, ttl: 10, max_size: 10
|
94
|
+
end
|
95
|
+
```
|
96
|
+
|
97
|
+
Output in Rails console:
|
98
|
+
|
99
|
+
```
|
100
|
+
Processing by TestController#index as HTML
|
101
|
+
Calling test_method(1, 2)
|
102
|
+
Calling test_method(5, 2)
|
103
|
+
Calling test_method(3, 4)
|
104
|
+
```
|
data/Rakefile
ADDED
@@ -0,0 +1,126 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "monitor"
|
4
|
+
|
5
|
+
module MemoTTL
|
6
|
+
# Internal cache with TTL (time-to-live) and max size enforcement.
|
7
|
+
class Cache
|
8
|
+
# Special object used to represent `nil` values safely.
|
9
|
+
NULL_OBJECT = Object.new.freeze
|
10
|
+
|
11
|
+
# Structure to hold a cached value and its expiration timestamp.
|
12
|
+
Entry = Struct.new(:value, :expires_at)
|
13
|
+
|
14
|
+
# Initializes a new Cache.
|
15
|
+
#
|
16
|
+
# @param max_size [Integer] maximum number of entries to keep
|
17
|
+
# @param ttl [Integer] time-to-live in seconds for each entry
|
18
|
+
# @raise [ArgumentError] if max_size or ttl are not positive integers
|
19
|
+
def initialize(max_size: 100, ttl: 60)
|
20
|
+
raise ArgumentError, "max_size must be a positive integer" unless max_size.is_a?(Integer) && max_size.positive?
|
21
|
+
raise ArgumentError, "ttl must be a positive integer" unless ttl.is_a?(Integer) && ttl.positive?
|
22
|
+
|
23
|
+
@max_size = max_size
|
24
|
+
@ttl = ttl
|
25
|
+
@store = {}
|
26
|
+
@order = []
|
27
|
+
@lock = Monitor.new
|
28
|
+
end
|
29
|
+
|
30
|
+
# Retrieves the cached value for a key, or nil if not present or expired.
|
31
|
+
#
|
32
|
+
# @param key [Object] the key to retrieve
|
33
|
+
# @return [Object, nil] the cached value or nil
|
34
|
+
# @raise [CacheOperationError] if there's an issue accessing the cache
|
35
|
+
def get(key)
|
36
|
+
@lock.synchronize do
|
37
|
+
entry = @store[key]
|
38
|
+
return nil unless entry
|
39
|
+
|
40
|
+
if entry.expires_at && Time.now > entry.expires_at
|
41
|
+
delete(key)
|
42
|
+
return nil
|
43
|
+
end
|
44
|
+
touch(key)
|
45
|
+
entry.value == NULL_OBJECT ? nil : entry.value
|
46
|
+
rescue StandardError => e
|
47
|
+
raise CacheOperationError, "Failed to get key #{key}: #{e.message}"
|
48
|
+
end
|
49
|
+
end
|
50
|
+
|
51
|
+
# Stores a value in the cache under the given key.
|
52
|
+
#
|
53
|
+
# @param key [Object] the key to store under
|
54
|
+
# @param value [Object, nil] the value to store
|
55
|
+
# @return [Object] the value that was stored
|
56
|
+
# @raise [CacheOperationError] if there's an issue storing in the cache
|
57
|
+
def set(key, value)
|
58
|
+
@lock.synchronize do
|
59
|
+
evict if !@store.key?(key) && @store.size >= @max_size
|
60
|
+
delete(key) if @store.key?(key)
|
61
|
+
stored_value = value.nil? ? NULL_OBJECT : value
|
62
|
+
@store[key] = Entry.new(stored_value, Time.now + @ttl)
|
63
|
+
@order.unshift(key)
|
64
|
+
value
|
65
|
+
rescue StandardError => e
|
66
|
+
raise CacheOperationError, "Failed to set key #{key}: #{e.message}"
|
67
|
+
end
|
68
|
+
end
|
69
|
+
|
70
|
+
# Removes all expired entries from the cache.
|
71
|
+
#
|
72
|
+
# @return [Integer] number of entries removed
|
73
|
+
# @raise [CacheOperationError] if there's an issue during cleanup
|
74
|
+
def cleanup
|
75
|
+
@lock.synchronize do
|
76
|
+
now = Time.now
|
77
|
+
expired_keys = @store.select { |_key, entry| entry.expires_at && now > entry.expires_at }.keys
|
78
|
+
expired_keys.each { |key| delete(key) }
|
79
|
+
expired_keys.size
|
80
|
+
rescue StandardError => e
|
81
|
+
raise CacheOperationError, "Failed during cache cleanup: #{e.message}"
|
82
|
+
end
|
83
|
+
end
|
84
|
+
|
85
|
+
# Checks if a key exists in the cache, regardless of its value.
|
86
|
+
#
|
87
|
+
# @param key [Object] the key to check
|
88
|
+
# @return [Boolean] true if the key exists, false otherwise
|
89
|
+
def key?(key)
|
90
|
+
@lock.synchronize { @store.key?(key) }
|
91
|
+
end
|
92
|
+
|
93
|
+
# Returns the number of current entries in the cache.
|
94
|
+
#
|
95
|
+
# @return [Integer]
|
96
|
+
def size
|
97
|
+
@lock.synchronize { @store.size }
|
98
|
+
end
|
99
|
+
|
100
|
+
private
|
101
|
+
|
102
|
+
# Deletes an entry by key.
|
103
|
+
#
|
104
|
+
# @param key [Object] the key to remove
|
105
|
+
def delete(key)
|
106
|
+
@store.delete(key)
|
107
|
+
@order.delete(key)
|
108
|
+
end
|
109
|
+
|
110
|
+
# Removes the least recently used entry.
|
111
|
+
#
|
112
|
+
# @return [void]
|
113
|
+
def evict
|
114
|
+
oldest_key = @order.pop
|
115
|
+
@store.delete(oldest_key)
|
116
|
+
end
|
117
|
+
|
118
|
+
# Marks a key as most recently used.
|
119
|
+
#
|
120
|
+
# @param key [Object] the key to touch
|
121
|
+
def touch(key)
|
122
|
+
@order.delete(key)
|
123
|
+
@order.unshift(key) unless @order.first == key
|
124
|
+
end
|
125
|
+
end
|
126
|
+
end
|
@@ -0,0 +1,45 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "cache"
|
4
|
+
|
5
|
+
module MemoTTL
|
6
|
+
# Adds class-level method memoization.
|
7
|
+
module ClassMethods
|
8
|
+
# Memoizes an instance method with TTL and max size.
|
9
|
+
#
|
10
|
+
# @param method_name [Symbol] the name of the method to memoize
|
11
|
+
# @param ttl [Integer] time-to-live in seconds for the memoized result
|
12
|
+
# @param max_size [Integer] maximum number of memoized results to keep
|
13
|
+
# @raise [NameError] if the method doesn't exist
|
14
|
+
# @raise [ArgumentError] if ttl or max_size are invalid
|
15
|
+
def memoize(method_name, ttl: 60, max_size: 100)
|
16
|
+
raise ArgumentError, "ttl must be positive" unless ttl.is_a?(Numeric) && ttl.positive?
|
17
|
+
raise ArgumentError, "max_size must be positive" unless max_size.is_a?(Integer) && max_size.positive?
|
18
|
+
|
19
|
+
unless method_defined?(method_name) || private_method_defined?(method_name)
|
20
|
+
raise NameError, "Method '#{method_name}' not defined in #{self}"
|
21
|
+
end
|
22
|
+
|
23
|
+
original_method = instance_method(method_name)
|
24
|
+
cache_var = "@__memo_ttl_cache__#{method_name}"
|
25
|
+
|
26
|
+
define_memoized_method(method_name, cache_var, original_method, ttl, max_size)
|
27
|
+
end
|
28
|
+
|
29
|
+
private
|
30
|
+
|
31
|
+
def define_memoized_method(method_name, cache_var, original_method, ttl, max_size)
|
32
|
+
warn "Redefining memoized method: #{method_name}" if instance_variable_defined?(cache_var)
|
33
|
+
|
34
|
+
define_method(method_name) do |*args, &block|
|
35
|
+
cache = fetch_or_create_cache(cache_var, ttl, max_size)
|
36
|
+
key = build_cache_key(method_name, args, block)
|
37
|
+
fetch_or_compute_result(cache, key, original_method, args, block)
|
38
|
+
rescue MemoTTL::KeyGenerationError, MemoTTL::MethodBindingError, MemoTTL::CacheOperationError => e
|
39
|
+
raise e
|
40
|
+
rescue StandardError => e
|
41
|
+
raise MemoTTL::Error, "Failed to execute memoized method '#{method_name}': #{e.message}"
|
42
|
+
end
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
@@ -0,0 +1,120 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "digest"
|
4
|
+
|
5
|
+
module MemoTTL
|
6
|
+
# Provides instance-level methods to manage memoized caches.
|
7
|
+
module InstanceMethods
|
8
|
+
# Clears the cache for a specific memoized method.
|
9
|
+
#
|
10
|
+
# @param method_name [Symbol] the method whose cache to clear
|
11
|
+
# @return [Boolean] true if cache was cleared, false if not found
|
12
|
+
def clear_memoized_method(method_name)
|
13
|
+
cache_var = "@__memo_ttl_cache__#{method_name}"
|
14
|
+
if instance_variable_defined?(cache_var)
|
15
|
+
remove_instance_variable(cache_var)
|
16
|
+
memo_registry.delete(method_name)
|
17
|
+
true
|
18
|
+
else
|
19
|
+
false
|
20
|
+
end
|
21
|
+
end
|
22
|
+
|
23
|
+
# Clears all memoized method caches for the current instance.
|
24
|
+
#
|
25
|
+
# @return [Integer] number of caches cleared
|
26
|
+
def clear_all_memoized_methods
|
27
|
+
return 0 unless defined?(@memo_registry)
|
28
|
+
|
29
|
+
@memo_registry.each do |method_name|
|
30
|
+
cache_var = "@__memo_ttl_cache__#{method_name}"
|
31
|
+
remove_instance_variable(cache_var) if instance_variable_defined?(cache_var)
|
32
|
+
end
|
33
|
+
|
34
|
+
count = @memo_registry.size
|
35
|
+
@memo_registry.clear
|
36
|
+
count
|
37
|
+
end
|
38
|
+
|
39
|
+
# Cleans up expired entries in all memoized caches.
|
40
|
+
#
|
41
|
+
# @return [Hash] results of cleanup operation for each cache
|
42
|
+
def cleanup_memoized_methods
|
43
|
+
results = {}
|
44
|
+
return results unless defined?(@memo_registry)
|
45
|
+
|
46
|
+
@memo_registry.each do |method_name|
|
47
|
+
cache_var = "@__memo_ttl_cache__#{method_name}"
|
48
|
+
next unless instance_variable_defined?(cache_var)
|
49
|
+
|
50
|
+
cache = instance_variable_get(cache_var)
|
51
|
+
|
52
|
+
begin
|
53
|
+
cache.cleanup
|
54
|
+
results[method_name] = :success
|
55
|
+
rescue MemoTTL::CacheOperationError => e
|
56
|
+
results[method_name] = e.message
|
57
|
+
end
|
58
|
+
end
|
59
|
+
results
|
60
|
+
end
|
61
|
+
|
62
|
+
# Checks if a memoized cache exists for a given method.
|
63
|
+
#
|
64
|
+
# @param method_name [Symbol]
|
65
|
+
# @return [Boolean]
|
66
|
+
def memoized?(method_name)
|
67
|
+
instance_variable_defined?("@__memo_ttl_cache__#{method_name}")
|
68
|
+
end
|
69
|
+
|
70
|
+
private
|
71
|
+
|
72
|
+
def memo_registry
|
73
|
+
@memo_registry ||= Set.new
|
74
|
+
end
|
75
|
+
|
76
|
+
def fetch_or_create_cache(cache_var, ttl, max_size)
|
77
|
+
return instance_variable_get(cache_var) if instance_variable_defined?(cache_var)
|
78
|
+
|
79
|
+
begin
|
80
|
+
cache = Cache.new(ttl: ttl, max_size: max_size)
|
81
|
+
instance_variable_set(cache_var, cache)
|
82
|
+
method_name = cache_var.to_s.sub("@__memo_ttl_cache__", "").to_sym
|
83
|
+
memo_registry << method_name
|
84
|
+
cache
|
85
|
+
rescue ArgumentError => e
|
86
|
+
raise MemoTTL::Error, "Failed to create cache: #{e.message}"
|
87
|
+
end
|
88
|
+
end
|
89
|
+
|
90
|
+
def build_cache_key(method_name, args, block)
|
91
|
+
block_hash =
|
92
|
+
if block.nil?
|
93
|
+
"no_block"
|
94
|
+
else
|
95
|
+
Digest::SHA256.hexdigest(block.source_location.inspect)
|
96
|
+
end
|
97
|
+
|
98
|
+
raw_key = [method_name, args, block_hash]
|
99
|
+
Digest::SHA256.hexdigest(Marshal.dump(raw_key))
|
100
|
+
rescue StandardError => e
|
101
|
+
raise KeyGenerationError, "Failed to generate cache key: #{e.message}"
|
102
|
+
end
|
103
|
+
|
104
|
+
def fetch_or_compute_result(cache, key, original_method, args, block)
|
105
|
+
result = cache.get(key)
|
106
|
+
return result unless result.nil? && !cache.key?(key)
|
107
|
+
|
108
|
+
begin
|
109
|
+
result = original_method.bind(self).call(*args, &block)
|
110
|
+
rescue NoMethodError => e
|
111
|
+
raise MethodBindingError, "Failed to bind method: #{e.message}"
|
112
|
+
rescue StandardError => e
|
113
|
+
raise e
|
114
|
+
end
|
115
|
+
|
116
|
+
cache.set(key, result)
|
117
|
+
result
|
118
|
+
end
|
119
|
+
end
|
120
|
+
end
|
data/lib/memo_ttl.rb
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "memo_ttl/version"
|
4
|
+
require_relative "memo_ttl/class_methods"
|
5
|
+
require_relative "memo_ttl/instance_methods"
|
6
|
+
|
7
|
+
# MemoTTL is a thread-safe memoization utility with TTL and LRU eviction.
|
8
|
+
module MemoTTL
|
9
|
+
class Error < StandardError; end
|
10
|
+
class KeyGenerationError < Error; end
|
11
|
+
class MethodBindingError < Error; end
|
12
|
+
class CacheOperationError < Error; end
|
13
|
+
|
14
|
+
# Hook that wires ClassMethods and InstanceMethods when the module is included.
|
15
|
+
#
|
16
|
+
# @param base [Class] the class including MemoTTL
|
17
|
+
def self.included(base)
|
18
|
+
base.extend(ClassMethods)
|
19
|
+
base.include(InstanceMethods)
|
20
|
+
end
|
21
|
+
end
|
data/sig/memo_ttl.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,59 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: memo_ttl
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.9.21
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Mishal Zaman
|
8
|
+
bindir: exe
|
9
|
+
cert_chain: []
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
11
|
+
dependencies: []
|
12
|
+
description: Adds memoization to methods with optional time-to-live and LRU eviction
|
13
|
+
email:
|
14
|
+
- mishalzaman@gmail.com
|
15
|
+
executables: []
|
16
|
+
extensions: []
|
17
|
+
extra_rdoc_files: []
|
18
|
+
files:
|
19
|
+
- ".rspec"
|
20
|
+
- ".rspec_status"
|
21
|
+
- ".rubocop.yml"
|
22
|
+
- CHANGELOG.md
|
23
|
+
- CODE_OF_CONDUCT.md
|
24
|
+
- LICENSE
|
25
|
+
- LICENSE.txt
|
26
|
+
- README.md
|
27
|
+
- Rakefile
|
28
|
+
- lib/memo_ttl.rb
|
29
|
+
- lib/memo_ttl/cache.rb
|
30
|
+
- lib/memo_ttl/class_methods.rb
|
31
|
+
- lib/memo_ttl/instance_methods.rb
|
32
|
+
- lib/memo_ttl/version.rb
|
33
|
+
- sig/memo_ttl.rbs
|
34
|
+
homepage: https://github.com/mishalzaman/memo_ttl
|
35
|
+
licenses:
|
36
|
+
- MIT
|
37
|
+
metadata:
|
38
|
+
allowed_push_host: https://rubygems.org
|
39
|
+
homepage_uri: https://github.com/mishalzaman/memo_ttl
|
40
|
+
source_code_uri: https://github.com/mishalzaman/memo_ttl
|
41
|
+
changelog_uri: https://github.com/mishalzaman/memo_ttl/blob/main/CHANGELOG.md
|
42
|
+
rdoc_options: []
|
43
|
+
require_paths:
|
44
|
+
- lib
|
45
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
46
|
+
requirements:
|
47
|
+
- - ">="
|
48
|
+
- !ruby/object:Gem::Version
|
49
|
+
version: 3.1.0
|
50
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
51
|
+
requirements:
|
52
|
+
- - ">="
|
53
|
+
- !ruby/object:Gem::Version
|
54
|
+
version: '0'
|
55
|
+
requirements: []
|
56
|
+
rubygems_version: 3.6.7
|
57
|
+
specification_version: 4
|
58
|
+
summary: Memoization with LRU and TTL
|
59
|
+
test_files: []
|