pakiderm 2.0.0 → 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
- SHA1:
3
- metadata.gz: 5a06111ba9f942e52a25123a6bd971bd9d589aee
4
- data.tar.gz: 1c44ca4ae3fde3db92211845f9c9d17102929ce5
2
+ SHA256:
3
+ metadata.gz: e8ec2e82bcb28b17ae2f38cd49cd65374c92d5c385de0adc3a19d8727dcf5111
4
+ data.tar.gz: 2aeb401bb66c7c00152c17d380025200c841998beda60ea10975b61a6ffd2b75
5
5
  SHA512:
6
- metadata.gz: f982969d4f44cdd49b75b7f51bcbd927578ffc25c085f776b464684acedf85332222db71c403d193594a92b60fb21f2f8d61c1220175f1ee93cf761e5268f9dc
7
- data.tar.gz: 59ba25e547895beaa4d345b3ff7a1b9c14551e5671be21c67948590fafddd534dcbe14efaf3ff7354e6bad9d5f2f46869b52a475bcfe7fde26b434c08d0d4454
6
+ metadata.gz: 36829cae9492a8209de0709446541828f2d2008cd5122539dc832c28f535628989b3df12fba12624e5681f5b5507283fb65b4d61c6c1d9b8d65d3d1ba138a236
7
+ data.tar.gz: 5a2a336b8e8cb59d4ca96361210b808010b6639ae703e40d6e2d8d3ca7bd4885671bd3cb127bb048c4f69a5e4be1f0fe3c4e9eca4ba0c11dcd135f84a852df1f
data/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
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
+
7
+ ## Pakiderm 2.0.1 (2021-02-24) ##
8
+
9
+ * Remove `ruby_version` restriction from gemspec to allow usage in Ruby 3.0.
10
+
11
+ ## Pakiderm 2.0.0 (2017-04-02) ##
12
+
13
+ * Use a lighter memoization stragegy based on `instance_variable_defined?`.
14
+ * Remove support for `assignable`; not that useful in practice.
data/README.md CHANGED
@@ -1,67 +1,72 @@
1
- Pakiderm
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
- [![Gem Version](https://badge.fury.io/rb/pakiderm.svg)](http://badge.fury.io/rb/pakiderm)
5
- [![Build Status](https://travis-ci.org/ElMassimo/pakiderm.svg)](https://travis-ci.org/ElMassimo/pakiderm)
6
- [![Coverage Status](https://coveralls.io/repos/github/ElMassimo/pakiderm/badge.svg?branch=master)](https://coveralls.io/github/ElMassimo/pakiderm?branch=master)
7
- [![Inline docs](http://inch-ci.org/github/ElMassimo/pakiderm.svg)](http://inch-ci.org/github/ElMassimo/pakiderm)
8
- [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ElMassimo/queryable/blob/master/LICENSE.txt)
4
+ Allows you to unobtrusively memoize methods without parameters. Pakiderm 3 requires Ruby 3.3.5 or newer.
9
5
 
10
- Allows you to unobtrusively memoize simple methods.
11
-
12
- ## Usage
13
6
  ```ruby
14
- class Counter
7
+ class Stopwatch
15
8
  extend Pakiderm
16
9
 
17
- memoize \
18
- def increment
19
- @sum = 1 + @sum.to_i
10
+ def start
11
+ @started_at = Time.now
12
+ end
13
+
14
+ def stop
15
+ elapsed_time
16
+ end
17
+
18
+ memoize
19
+ def elapsed_time
20
+ Time.now - @started_at
20
21
  end
21
22
  end
22
23
  ```
23
- Your method will only be called the first time, the result will be stored and returned on subsequent invocations.
24
- ```irb
25
- counter = Counter.new
26
- => Counter
27
24
 
28
- counter.increment
29
- => 1
25
+ The first call computes the result. Subsequent calls on the same object return the stored value, even if it is `nil` or `false`.
30
26
 
31
- counter.increment
32
- => 1
27
+ ```ruby
28
+ stopwatch = Stopwatch.new
29
+ stopwatch.start
30
+ stopwatch.stop # Example: 3.991826
31
+ stopwatch.elapsed_time # => 3.991826
33
32
  ```
34
- 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
+
35
36
  ```ruby
36
37
  memoize :complex_calculation, :api_response, :db_query
37
38
  ```
38
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
+
39
46
  ## Background
40
- 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.
41
64
 
42
65
  ### Caveat
43
- If you override the method in a subclass, Pakiderm's method won't be able to intercept calls to the subclass' method.
44
-
45
- License
46
- --------
47
-
48
- Copyright (c) 2014 Máximo Mussini
49
-
50
- Permission is hereby granted, free of charge, to any person obtaining
51
- a copy of this software and associated documentation files (the
52
- "Software"), to deal in the Software without restriction, including
53
- without limitation the rights to use, copy, modify, merge, publish,
54
- distribute, sublicense, and/or sell copies of the Software, and to
55
- permit persons to whom the Software is furnished to do so, subject to
56
- the following conditions:
57
-
58
- The above copyright notice and this permission notice shall be
59
- included in all copies or substantial portions of the Software.
60
-
61
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
62
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
63
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
64
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
65
- LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
66
- OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
67
- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
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.0'
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
- # NSA.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 :tired?, :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.0
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: 2017-04-03 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
@@ -32,31 +37,30 @@ extensions: []
32
37
  extra_rdoc_files:
33
38
  - README.md
34
39
  files:
40
+ - CHANGELOG.md
35
41
  - README.md
36
42
  - lib/pakiderm.rb
43
+ - lib/pakiderm/recompiler.rb
37
44
  - lib/pakiderm/version.rb
38
45
  homepage: https://github.com/ElMassimo/pakiderm
39
46
  licenses:
40
47
  - MIT
41
48
  metadata: {}
42
- post_install_message:
43
49
  rdoc_options: []
44
50
  require_paths:
45
51
  - lib
46
52
  required_ruby_version: !ruby/object:Gem::Requirement
47
53
  requirements:
48
- - - "~>"
54
+ - - ">="
49
55
  - !ruby/object:Gem::Version
50
- version: '2.0'
56
+ version: 3.3.5
51
57
  required_rubygems_version: !ruby/object:Gem::Requirement
52
58
  requirements:
53
59
  - - ">="
54
60
  - !ruby/object:Gem::Version
55
61
  version: '0'
56
62
  requirements: []
57
- rubyforge_project:
58
- rubygems_version: 2.5.1
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: []