pakiderm 2.0.1 → 3.0.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '08f9f75542494482d1a1a556c39f4b96c3711807aef701e90e51f9ff709515ac'
4
- data.tar.gz: a6d903bd7a22835612c141f2cad52fbe9f28ca552ce829c46730977aae3f2f88
3
+ metadata.gz: e8ec2e82bcb28b17ae2f38cd49cd65374c92d5c385de0adc3a19d8727dcf5111
4
+ data.tar.gz: 2aeb401bb66c7c00152c17d380025200c841998beda60ea10975b61a6ffd2b75
5
5
  SHA512:
6
- metadata.gz: 301114c77d1a62bba6f9ec3405551dc5d1a89c99290baee180e2ecb0eee33f8bd8b33946e19c0c93a63b074a7e9eb253670a7cb86668eb3553d29742741d6ac9
7
- data.tar.gz: 5e465d6aaec3106149eae792501583fe2c24660fa2ac5073e105659e0301cdacf38963624457a48e5a0cc89574ff76db9aaa1b4192275cae598d8db7f09af3a2
6
+ metadata.gz: 36829cae9492a8209de0709446541828f2d2008cd5122539dc832c28f535628989b3df12fba12624e5681f5b5507283fb65b4d61c6c1d9b8d65d3d1ba138a236
7
+ data.tar.gz: 5a2a336b8e8cb59d4ca96361210b808010b6639ae703e40d6e2d8d3ca7bd4885671bd3cb127bb048c4f69a5e4be1f0fe3c4e9eca4ba0c11dcd135f84a852df1f
data/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## Pakiderm 3.0.0 (2026-12-03)
2
+
3
+ * Support Ruby 3.3.5+. Put `memoize` directly above a method definition.
4
+ * Compile readers into direct ivar access at load time rather than prepending wrappers. Preserve visibility, source lines, and independent caches for memoized overrides.
5
+ * Named declarations now require an existing, local, source-backed `def`. See the README for migration notes and unsupported forms.
6
+
1
7
  ## Pakiderm 2.0.1 (2021-02-24) ##
2
8
 
3
9
  * Remove `ruby_version` restriction from gemspec to allow usage in Ruby 3.0.
data/README.md CHANGED
@@ -1,7 +1,7 @@
1
- Pakiderm [![Gem Version](https://badge.fury.io/rb/pakiderm.svg)](http://badge.fury.io/rb/pakiderm) [![Build Status](https://github.com/ElMassimo/pakiderm/workflows/build/badge.svg)](https://github.com/ElMassimo/pakiderm/actions) [![Test Coverage](https://codeclimate.com/github/ElMassimo/pakiderm/badges/coverage.svg)](https://codeclimate.com/github/ElMassimo/pakiderm) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ElMassimo/queryable/blob/master/LICENSE.txt)
1
+ Pakiderm [![Gem Version](https://img.shields.io/gem/v/pakiderm)](https://rubygems.org/gems/pakiderm) [![Build Status](https://github.com/ElMassimo/pakiderm/actions/workflows/ruby.yml/badge.svg?branch=main)](https://github.com/ElMassimo/pakiderm/actions/workflows/ruby.yml) [![Test Coverage](https://qlty.sh/gh/ElMassimo/projects/pakiderm/coverage.svg)](https://qlty.sh/gh/ElMassimo/projects/pakiderm) [![Maintainability](https://qlty.sh/gh/ElMassimo/projects/pakiderm/maintainability.svg)](https://qlty.sh/gh/ElMassimo/projects/pakiderm) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE.txt)
2
2
  =====================
3
3
 
4
- Allows you to unobtrusively memoize methods without parameters.
4
+ Allows you to unobtrusively memoize methods without parameters. Pakiderm 3 requires Ruby 3.3.5 or newer.
5
5
 
6
6
  ```ruby
7
7
  class Stopwatch
@@ -15,26 +15,58 @@ class Stopwatch
15
15
  elapsed_time
16
16
  end
17
17
 
18
- memoize \
18
+ memoize
19
19
  def elapsed_time
20
20
  Time.now - @started_at
21
21
  end
22
22
  end
23
23
  ```
24
- Memoized methods will only be called the first time; the result will be stored and returned on subsequent invocations.
24
+
25
+ The first call computes the result. Subsequent calls on the same object return the stored value, even if it is `nil` or `false`.
26
+
25
27
  ```ruby
26
28
  stopwatch = Stopwatch.new
27
29
  stopwatch.start
28
30
  stopwatch.stop # Example: 3.991826
29
31
  stopwatch.elapsed_time # => 3.991826
30
32
  ```
31
- You can also pass a list of methods that should be memoized:
33
+
34
+ You can also pass a list of methods after defining them on the same class or module:
35
+
32
36
  ```ruby
33
37
  memoize :complex_calculation, :api_response, :db_query
34
38
  ```
35
39
 
40
+ ## Releasing
41
+
42
+ Update `lib/pakiderm/version.rb`, `Gemfile.lock`, and `CHANGELOG.md` for the release. Commit and push those changes, then wait for CI to pass on `main`.
43
+
44
+ From a clean, up-to-date `main` with RubyGems push access, run `bin/rake release`. It runs the specs, builds the gem, pushes the `v<version>` tag, and publishes the gem to RubyGems. The tag push triggers the GitHub Release workflow. To check the specs and package without publishing, run `bin/rake spec build` instead.
45
+
36
46
  ## Background
37
- Pakiderm adds a method by using `Module#prepend` in order to"intercept" calls to the original method and provide memoization.
47
+
48
+ Pakiderm 2 used `Module#prepend` to put a wrapper in front of each memoized method. Even a cache hit went through that wrapper and called `instance_variable_defined?` and `instance_variable_get`.
49
+
50
+ ### Compiling the cache into the method
51
+
52
+ In Pakiderm 3, `memoize` marks the next definition. When Ruby calls `method_added`, Pakiderm uses Prism to find the original `def` and recompiles it in place. For the stopwatch above, the result is equivalent to writing this by hand (the actual instance variable name is private to Pakiderm):
53
+
54
+ ```ruby
55
+ def elapsed_time
56
+ return @elapsed_time if defined?(@elapsed_time)
57
+ @elapsed_time = Time.now - @started_at
58
+ end
59
+ ```
60
+
61
+ The parsing cost is paid when the class loads, not when you call the method. A cache hit reads the instance variable directly, with no wrapper call. You can compare compiled and handwritten readers with `bundle exec ruby --yjit benchmark/readers.rb`.
62
+
63
+ The method keeps its visibility and its place in Ruby's lookup order. A module prepended before the definition can still call `super`. A subclass can memoize an override that calls `super`, too: the parent and child store their results separately. No hidden alias is needed. An alias made after memoizing uses the cache; an earlier alias still calls the original method.
38
64
 
39
65
  ### Caveat
40
- If you override the method in a subclass, Pakiderm's method won't be able to intercept calls to the subclass' method, so you would need to call `memoize` again in the subclass.
66
+
67
+ An override is a new method: annotate it again if you want it memoized. The old `memoize def` and backslash forms still work, but neither is required. For class methods, put `memoize` above `def self.name`, or `extend Pakiderm` inside `class << self`.
68
+
69
+ - Choose a parameterless `def` in a Ruby source file. Pakiderm rejects explicit `return`, operator names, aliases, and generated readers such as `attr_reader`. Don't memoize a result that depends on a caller's block.
70
+ - Pakiderm preserves source lines, lexical constants, and frozen-string settings. Files that activate refinements with `using`, dynamic class or module paths around the reader, and `class << self` inside a block with unknown `self` aren't supported.
71
+ - Custom method-added hooks must call `super` and can see both definitions. To export a module function, use `module_function :name` **after** memoizing; bare `module_function` mode leaves the module-level copy uncached.
72
+ - As with handwritten memoization, an exception is not cached, a cache miss cannot write to a frozen receiver, and concurrent first calls are not synchronized.
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "prism"
4
+
5
+ module Pakiderm
6
+ module Recompiler
7
+ ParsedFile = Struct.new(:version, :pragma, :definitions, :refinements)
8
+
9
+ class << self
10
+ def install(owner, name)
11
+ method = owner.instance_method(name)
12
+ method = method.super_method until method.nil? || method.owner.equal?(owner)
13
+ raise Error, "`#{name}` must be defined on #{owner}" unless method
14
+ raise Error, "cannot memoize an alias: `#{name}`" unless method.original_name == name
15
+
16
+ definition = compile(owner, name, method.source_location)
17
+ visibility = if owner.private_method_defined?(name, false)
18
+ :private
19
+ elsif owner.protected_method_defined?(name, false)
20
+ :protected
21
+ else
22
+ :public
23
+ end
24
+ owner.send(:remove_method, name)
25
+ owner.class_eval(&definition)
26
+ owner.send(visibility, name)
27
+ end
28
+
29
+ private
30
+
31
+ def compile(owner, name, location)
32
+ path, line = location
33
+ raise Error, "`#{name}` is not defined in a source file" unless path && File.file?(path)
34
+
35
+ file = parsed(path)
36
+ raise Error, "#{path} activates refinements; cannot recompile `#{name}`" if file.refinements
37
+
38
+ node, nesting = file.definitions[[name, line]]
39
+ raise Error, "cannot locate an unambiguous `def #{name}` at #{path}:#{line}" unless node
40
+ raise Error, "unsupported lexical nesting at #{path}:#{line}" unless nesting
41
+
42
+ # Reopen the lexical nesting, not just the owner: a Class.new block, for
43
+ # example, gets its constants from the scope around it.
44
+ statements = [*nesting, "proc { #{memoized(owner, node)} }", *nesting.map { "end" }].join("; ")
45
+ TOPLEVEL_BINDING.eval("#{file.pragma}\n#{statements}", path, line - 1)
46
+ rescue SyntaxError => error
47
+ raise Error, "cannot recompile `#{name}` at #{path}:#{line}: #{error.message}"
48
+ end
49
+
50
+ def memoized(owner, node)
51
+ name = node.name
52
+ raise Error, "`#{name}` takes arguments" if node.parameters
53
+ if node.body&.breadth_first_search { |child| child.is_a?(Prism::ReturnNode) }
54
+ raise Error, "`#{name}` has an explicit return that could bypass the cache"
55
+ end
56
+
57
+ match = /\A([a-z_]\w*)([?!]?)\z/i.match(name)
58
+ raise Error, "unsupported method name: `#{name}`" unless match
59
+
60
+ kind = { "?" => "question", "!" => "bang", "" => "reader" }.fetch(match[2])
61
+ ivar = "@pakiderm_#{owner.object_id}_#{kind}_#{match[1]}"
62
+ guard = "; return #{ivar} if defined?(#{ivar}); #{ivar} = "
63
+ source = node.slice
64
+ start = node.location.start_offset
65
+ split = (node.equal_loc || node.rparen_loc || node.name_loc).end_offset - start
66
+ header = source.byteslice(0, split)
67
+ header = header.delete_suffix("=") if node.equal_loc
68
+ if node.receiver
69
+ # The destination is already the singleton class. Keep any newlines in
70
+ # the receiver so backtraces still point to the original body.
71
+ first = node.receiver.location.start_offset - start
72
+ last = node.operator_loc.end_offset - start
73
+ header = header.byteslice(0, first) + header.byteslice(first...last).gsub(/[^\n]/, " ") + header.byteslice(last..)
74
+ end
75
+
76
+ if node.equal_loc
77
+ "#{header}#{guard}(#{source.byteslice(split..)}); end"
78
+ else
79
+ body = source.byteslice(split...(node.end_keyword_loc.start_offset - start))
80
+ "#{header}#{guard}begin#{body}end; end"
81
+ end
82
+ end
83
+
84
+ def parsed(path)
85
+ version = [path, File.mtime(path)]
86
+ file = @last_parsed
87
+ return file if file&.version == version
88
+
89
+ result = Prism.parse_file(path)
90
+ raise Error, "cannot parse #{path}" unless result.success?
91
+
92
+ pragma = result.magic_comments.find { |comment| comment.key == "frozen_string_literal" }
93
+ settings = ["coding: #{result.encoding.name}"]
94
+ settings << "frozen_string_literal: #{pragma.value}" if pragma
95
+ file = ParsedFile.new(version, "# -*- #{settings.join("; ")} -*-", {}, false)
96
+ index(result.value, [], file)
97
+ @last_parsed = file
98
+ end
99
+
100
+ def index(node, nesting, file, static_self: true)
101
+ case node
102
+ when Prism::DefNode
103
+ if !node.receiver || node.receiver.is_a?(Prism::SelfNode)
104
+ key = [node.name, node.location.start_line]
105
+ file.definitions[key] = file.definitions.key?(key) ? nil : [node, nesting]
106
+ end
107
+ return
108
+ when Prism::BlockNode, Prism::LambdaNode
109
+ static_self = false
110
+ when Prism::ClassNode, Prism::ModuleNode
111
+ static_self = true
112
+ keyword = node.is_a?(Prism::ClassNode) ? "class" : "module"
113
+ nesting = begin
114
+ nesting + ["#{keyword} #{node.constant_path.full_name}"] if nesting
115
+ rescue Prism::ConstantPathNode::DynamicPartsInConstantPathError
116
+ nil
117
+ end
118
+ when Prism::SingletonClassNode
119
+ nesting = nesting + ["class << self"] if nesting
120
+ nesting = nil unless static_self && node.expression.is_a?(Prism::SelfNode)
121
+ when Prism::CallNode
122
+ file.refinements = true if node.name == :using && (!node.receiver || node.receiver.is_a?(Prism::SelfNode))
123
+ end
124
+
125
+ node.compact_child_nodes.each { |child| index(child, nesting, file, static_self:) }
126
+ end
127
+ end
128
+ end
129
+ private_constant :Recompiler
130
+ end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Pakiderm
2
- VERSION = '2.0.1'
4
+ VERSION = "3.0.0"
3
5
  end
data/lib/pakiderm.rb CHANGED
@@ -1,50 +1,52 @@
1
- # Public: Mixin that adds memoization functionality to a plain ruby object.
2
- # Memoization is selectively applied to methods by using the `memoize` method.
3
- #
4
- # Examples
5
- #
6
- # class PersonQuery
7
- # extend Pakiderm
8
- #
9
- # memoize \
10
- # def recent_activity
11
- # Activities.get("/api/#{person.id}")
12
- # end
13
- # end
14
- #
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "pakiderm/recompiler"
4
+ require_relative "pakiderm/version"
5
+
15
6
  module Pakiderm
16
- # Public: Adds memoization to methods without parameters using Module#prepend.
17
- #
18
- # names - Names of the methods to be memoized.
19
- #
20
- # Examples
21
- #
22
- # memoize :ready?, :complex_formula, :long_running_method!
23
- #
24
- # Returns nothing.
7
+ Error = Class.new(StandardError)
8
+
25
9
  def memoize(*names)
26
- prepend Module.new {
27
- names.each do |name|
28
- ivar = Pakiderm.memoized_ivar_for(name)
29
-
30
- define_method(name) {
31
- if instance_variable_defined?(ivar)
32
- instance_variable_get(ivar)
33
- else
34
- instance_variable_set(ivar, super())
35
- end
36
- }
37
- end
38
- }
10
+ if names.empty?
11
+ @_pakiderm_pending = true
12
+ else
13
+ names.each { |name| Recompiler.install(self, name.to_sym) }
14
+ end
15
+ names.last
16
+ end
17
+
18
+ private
19
+
20
+ def method_added(name)
21
+ install_pending_memo(self, name)
22
+ super
23
+ end
24
+
25
+ def singleton_method_added(name)
26
+ install_pending_memo(singleton_class, name)
27
+ super
28
+ end
29
+
30
+ def install_pending_memo(owner, name)
31
+ return unless @_pakiderm_pending
32
+
33
+ @_pakiderm_pending = false
34
+ Recompiler.install(owner, name)
39
35
  end
40
36
 
41
- # Internal: Creates a valid name for the instance variable used to store the
42
- # memoized value for a method.
43
- #
44
- # name - Name of the method to memoize.
45
- #
46
- # Returns a String.
47
- def self.memoized_ivar_for(name)
48
- "@pakiderm_#{ name.to_s.gsub('?', '_question_mark').sub('!', '_bang') }"
37
+ # Ruby reports a definition inside `class << self` to the attached object's
38
+ # singleton_method_added, not to the singleton class's method_added.
39
+ def self.extended(owner)
40
+ owner.include(SingletonDefinitions) if owner.singleton_class?
41
+ end
42
+
43
+ module SingletonDefinitions
44
+ private
45
+
46
+ def singleton_method_added(name)
47
+ singleton_class.send(:install_pending_memo, singleton_class, name)
48
+ super
49
+ end
49
50
  end
51
+ private_constant :SingletonDefinitions
50
52
  end
metadata CHANGED
@@ -1,29 +1,34 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: pakiderm
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.1
4
+ version: 3.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Máximo Mussini
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2021-02-24 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
- name: rspec-given
13
+ name: prism
15
14
  requirement: !ruby/object:Gem::Requirement
16
15
  requirements:
17
- - - "~>"
16
+ - - ">="
18
17
  - !ruby/object:Gem::Version
19
- version: '3.0'
20
- type: :development
18
+ version: '1.8'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '3'
22
+ type: :runtime
21
23
  prerelease: false
22
24
  version_requirements: !ruby/object:Gem::Requirement
23
25
  requirements:
24
- - - "~>"
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '1.8'
29
+ - - "<"
25
30
  - !ruby/object:Gem::Version
26
- version: '3.0'
31
+ version: '3'
27
32
  description: Pakiderm is a simple module that encapsulates a modern memoization technique.
28
33
  email:
29
34
  - maximomussini@gmail.com
@@ -35,12 +40,12 @@ files:
35
40
  - CHANGELOG.md
36
41
  - README.md
37
42
  - lib/pakiderm.rb
43
+ - lib/pakiderm/recompiler.rb
38
44
  - lib/pakiderm/version.rb
39
45
  homepage: https://github.com/ElMassimo/pakiderm
40
46
  licenses:
41
47
  - MIT
42
48
  metadata: {}
43
- post_install_message:
44
49
  rdoc_options: []
45
50
  require_paths:
46
51
  - lib
@@ -48,15 +53,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
48
53
  requirements:
49
54
  - - ">="
50
55
  - !ruby/object:Gem::Version
51
- version: '2.0'
56
+ version: 3.3.5
52
57
  required_rubygems_version: !ruby/object:Gem::Requirement
53
58
  requirements:
54
59
  - - ">="
55
60
  - !ruby/object:Gem::Version
56
61
  version: '0'
57
62
  requirements: []
58
- rubygems_version: 3.2.3
59
- signing_key:
63
+ rubygems_version: 4.0.20
60
64
  specification_version: 4
61
65
  summary: Pakiderm will never forget the return value.
62
66
  test_files: []