safe_memoize 0.1.0

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4806562a18a6f5143379d638d270ea3552280637dd33ed322c0f667f1257d836
4
+ data.tar.gz: bdb12e7ae3a41d230c85fd24750edcc5eeba4d90cf2ac93b59cd0bccc8ba0325
5
+ SHA512:
6
+ metadata.gz: 4799eb0209980d5fee072ae05ff1661d70b8db5869e8701cac3fcd9241c1106f17fa84a798f85bcb084c197c24c646e2996fe60fa7375d4db8d780ad3bc4b71a
7
+ data.tar.gz: 6d64a7e4bef4d5b3825d903294bc955c1ec483157aee479496e001cb500e6128804e148791793d862938543bf5e9e7ee05cca128adb4bb37e68a9d4858bcb517
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-02-26
4
+
5
+ - Initial release
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Chuck Smith
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,119 @@
1
+ # SafeMemoize
2
+
3
+ Thread-safe memoization for Ruby that correctly handles `nil` and `false` values.
4
+
5
+ ## The Problem
6
+
7
+ Ruby's common memoization pattern breaks with falsy values:
8
+
9
+ ```ruby
10
+ def user
11
+ @user ||= find_user # Re-runs find_user every time it returns nil!
12
+ end
13
+ ```
14
+
15
+ SafeMemoize uses `Hash#key?` to distinguish "not yet cached" from "cached nil/false", so your methods are only computed once regardless of return value.
16
+
17
+ ## Features
18
+
19
+ - Correctly memoizes `nil` and `false` return values
20
+ - Caches per unique arguments (positional and keyword)
21
+ - Thread-safe via double-check locking
22
+ - Zero runtime dependencies
23
+ - Simple `prepend` + `memoize` API
24
+ - Block arguments bypass cache (blocks aren't comparable)
25
+
26
+ ## Installation
27
+
28
+ Add to your Gemfile:
29
+
30
+ ```ruby
31
+ gem "safe_memoize"
32
+ ```
33
+
34
+ Then run:
35
+
36
+ ```bash
37
+ bundle install
38
+ ```
39
+
40
+ Or install directly:
41
+
42
+ ```bash
43
+ gem install safe_memoize
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ ### Basic memoization
49
+
50
+ ```ruby
51
+ class UserService
52
+ prepend SafeMemoize
53
+
54
+ def current_user
55
+ # This expensive lookup runs only once
56
+ User.find_by(session_id: session_id)
57
+ end
58
+ memoize :current_user
59
+ end
60
+ ```
61
+
62
+ ### With arguments
63
+
64
+ Results are cached per unique argument combination:
65
+
66
+ ```ruby
67
+ class Calculator
68
+ prepend SafeMemoize
69
+
70
+ def compute(x, y)
71
+ sleep(2)
72
+ x + y
73
+ end
74
+ memoize :compute
75
+ end
76
+
77
+ calc = Calculator.new
78
+ calc.compute(1, 2) # computes and caches
79
+ calc.compute(1, 2) # returns cached result
80
+ calc.compute(3, 4) # computes and caches (different args)
81
+ ```
82
+
83
+ ### Nil and false safety
84
+
85
+ ```ruby
86
+ class Config
87
+ prepend SafeMemoize
88
+
89
+ def enabled?
90
+ # Only called once, even though it returns false
91
+ ENV["FEATURE_FLAG"] == "true"
92
+ end
93
+ memoize :enabled?
94
+ end
95
+ ```
96
+
97
+ ### Cache reset
98
+
99
+ ```ruby
100
+ obj = MyService.new
101
+ obj.reset_memo(:current_user) # Clears cache for one method
102
+ obj.reset_all_memos # Clears all memoized values
103
+ ```
104
+
105
+ ## How It Works
106
+
107
+ SafeMemoize uses Ruby's `prepend` mechanism. When you call `memoize :method_name`, it creates an anonymous module with a wrapper method and prepends it onto your class. The wrapper calls `super` to invoke the original method and stores the result in a per-instance hash. Thread safety is achieved with a per-instance `Mutex` using double-check locking.
108
+
109
+ ## Development
110
+
111
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt.
112
+
113
+ ## Contributing
114
+
115
+ Bug reports and pull requests are welcome on GitHub at https://github.com/eclectic-coding/safe_memoize.
116
+
117
+ ## License
118
+
119
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[spec standard]
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SafeMemoize
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "safe_memoize/version"
4
+
5
+ module SafeMemoize
6
+ class Error < StandardError; end
7
+
8
+ def self.prepended(base)
9
+ base.extend(ClassMethods)
10
+ end
11
+
12
+ module ClassMethods
13
+ def memoize(method_name)
14
+ method_name = method_name.to_sym
15
+
16
+ mod = Module.new do
17
+ define_method(method_name) do |*args, **kwargs, &block|
18
+ # Blocks bypass cache entirely — they aren't comparable
19
+ return super(*args, **kwargs, &block) if block
20
+
21
+ cache_key = [method_name, args, kwargs]
22
+
23
+ @__safe_memo_mutex__ ||= Mutex.new
24
+
25
+ # Fast path: check without lock
26
+ if defined?(@__safe_memo_cache__) && @__safe_memo_cache__.key?(cache_key)
27
+ return @__safe_memo_cache__[cache_key]
28
+ end
29
+
30
+ # Slow path: lock and double-check
31
+ @__safe_memo_mutex__.synchronize do
32
+ @__safe_memo_cache__ ||= {}
33
+
34
+ if @__safe_memo_cache__.key?(cache_key)
35
+ @__safe_memo_cache__[cache_key]
36
+ else
37
+ @__safe_memo_cache__[cache_key] = super(*args, **kwargs)
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ prepend mod
44
+ end
45
+ end
46
+
47
+ def reset_memo(method_name)
48
+ method_name = method_name.to_sym
49
+
50
+ return unless defined?(@__safe_memo_cache__)
51
+
52
+ if defined?(@__safe_memo_mutex__) && @__safe_memo_mutex__
53
+ @__safe_memo_mutex__.synchronize do
54
+ @__safe_memo_cache__.delete_if { |key, _| key[0] == method_name }
55
+ end
56
+ else
57
+ @__safe_memo_cache__.delete_if { |key, _| key[0] == method_name }
58
+ end
59
+ end
60
+
61
+ def reset_all_memos
62
+ if defined?(@__safe_memo_mutex__) && @__safe_memo_mutex__
63
+ @__safe_memo_mutex__.synchronize do
64
+ @__safe_memo_cache__ = {}
65
+ end
66
+ else
67
+ @__safe_memo_cache__ = {}
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,12 @@
1
+ module SafeMemoize
2
+ VERSION: String
3
+
4
+ def self.prepended: (Class base) -> void
5
+
6
+ def reset_memo: (Symbol method_name) -> void
7
+ def reset_all_memos: () -> void
8
+
9
+ module ClassMethods
10
+ def memoize: (Symbol | String method_name) -> void
11
+ end
12
+ end
metadata ADDED
@@ -0,0 +1,53 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: safe_memoize
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Chuck Smith
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: A prepend-based memoization module for Ruby that safely caches nil and
13
+ false return values, supports method arguments, and provides thread safety via double-check
14
+ locking.
15
+ email:
16
+ - eclectic-coding@users.noreply.github.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - LICENSE.txt
23
+ - README.md
24
+ - Rakefile
25
+ - lib/safe_memoize.rb
26
+ - lib/safe_memoize/version.rb
27
+ - sig/safe_memoize.rbs
28
+ homepage: https://github.com/eclectic-coding/safe_memoize
29
+ licenses:
30
+ - MIT
31
+ metadata:
32
+ allowed_push_host: https://rubygems.org
33
+ homepage_uri: https://github.com/eclectic-coding/safe_memoize
34
+ source_code_uri: https://github.com/eclectic-coding/safe_memoize/tree/main
35
+ changelog_uri: https://github.com/eclectic-coding/safe_memoize/blob/main/CHANGELOG.md
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: 3.2.0
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubygems_version: 4.0.2
51
+ specification_version: 4
52
+ summary: Thread-safe memoization that correctly handles nil and false values
53
+ test_files: []