ddmemoize-1.0.0/0000755000175000017500000000000013336512126013045 5ustar boutilboutilddmemoize-1.0.0/Rakefile0000644000175000017500000000035613336512126014516 0ustar boutilboutil# frozen_string_literal: true require 'rubocop/rake_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) do |t| t.verbose = false end RuboCop::RakeTask.new(:rubocop) task default: :test task test: %i[spec rubocop] ddmemoize-1.0.0/.travis.yml0000644000175000017500000000031713336512126015157 0ustar boutilboutillanguage: ruby rvm: - "2.3" - "2.4" - "2.5" branches: only: - "master" before_install: - gem update --system - gem install bundler -v 1.16.0 cache: bundler sudo: false git: depth: 10 ddmemoize-1.0.0/.rspec0000644000175000017500000000006113336512126014157 0ustar boutilboutil-r ./spec/spec_helper.rb --format Fuubar --color ddmemoize-1.0.0/README.md0000644000175000017500000000546113336512126014332 0ustar boutilboutil[![Gem version](https://img.shields.io/gem/v/ddmemoize.svg)](http://rubygems.org/gems/ddmemoize) [![Gem downloads](https://img.shields.io/gem/dt/ddmemoize.svg)](http://rubygems.org/gems/ddmemoize) [![Build status](https://img.shields.io/travis/ddfreyne/ddmemoize.svg)](https://travis-ci.org/ddfreyne/ddmemoize) [![Code Climate](https://img.shields.io/codeclimate/github/ddfreyne/ddmemoize.svg)](https://codeclimate.com/github/ddfreyne/ddmemoize) [![Code Coverage](https://img.shields.io/codecov/c/github/ddfreyne/ddmemoize.svg)](https://codecov.io/gh/ddfreyne/ddmemoize) # DDMemoize _DDMemoize_ adds support for memoizing Ruby functions. For example, the following Fibonacci implementation runs quickly (in O(n) rather than in O(2^n)): ```ruby class FibFast DDMemoize.activate(self) memoized def run(n) if n == 0 0 elsif n == 1 1 else run(n - 1) + run(n - 2) end end end ``` Features: * Supports memoizing functions on frozen objects * Releases memoized values when needed in order to reduce memory pressure * Optionally records metrics ## Installation Add this line to your application's Gemfile: ```ruby gem 'ddmemoize' ``` And then execute: $ bundle Or install it yourself as: $ gem install ddmemoize ## Usage First, require `ddmemoize` and enable it using `DDMemoize.activate`: ```ruby require 'ddmemoize' class FibFast DDMemoize.activate(self) # … end ``` To memoize a function, call `memoize` with the name of the function: ```ruby def run(n) # … end memoize :run ``` Alternatively, prepend `memoized` to the function definition: ```ruby memoized def run(n) # … end ``` Do not memoize functions that depend on mutable state. ### Metrics To activate metrics, call `DDMemoize.enable_metrics` after requiring `ddmemoize`. To print the collected metrics, call `DDMemoize.print_metrics`: ```ruby DDMemoize.print_metrics ``` ``` memoization │ hit miss % ────────────┼─────────────────── FibFast#fib │ 998 1001 49.9% ``` ## Development Install dependencies: $ bundle Run tests: $ bundle exec rake ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/ddfreyne/ddmemoize. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). ## Code of Conduct Everyone interacting in the DDMemoize project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ddfreyne/ddmemoize/blob/master/CODE_OF_CONDUCT.md). ddmemoize-1.0.0/ddmemoize.gemspec0000644000175000017500000000123113336512126016364 0ustar boutilboutil# frozen_string_literal: true require_relative 'lib/ddmemoize/version' Gem::Specification.new do |spec| spec.name = 'ddmemoize' spec.version = DDMemoize::VERSION spec.authors = ['Denis Defreyne'] spec.email = ['denis+rubygems@denis.ws'] spec.summary = 'Adds support for memoizing functions' spec.homepage = 'https://github.com/ddfreyne/ddmemoize' spec.license = 'MIT' spec.required_ruby_version = '>= 2.3.0' spec.add_runtime_dependency('ddmetrics', '~> 1.0') spec.add_runtime_dependency('ref', '~> 2.0') spec.files = `git ls-files -z`.split("\x0") spec.require_paths = ['lib'] end ddmemoize-1.0.0/.gitignore0000644000175000017500000000006313336512126015034 0ustar boutilboutil.DS_Store *.gem /.vscode/ /coverage/ /Gemfile.lock ddmemoize-1.0.0/Gemfile0000644000175000017500000000030013336512126014331 0ustar boutilboutil# frozen_string_literal: true source 'https://rubygems.org' gemspec group :devel do gem 'codecov', require: false gem 'fuubar' gem 'rake' gem 'rspec' gem 'rubocop', '~> 0.50' end ddmemoize-1.0.0/CODE_OF_CONDUCT.md0000644000175000017500000000624413336512126015652 0ustar boutilboutil# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at denis.defreyne@stoneship.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ddmemoize-1.0.0/scripts/0000755000175000017500000000000013336512126014534 5ustar boutilboutilddmemoize-1.0.0/scripts/release0000755000175000017500000000530613336512126016106 0ustar boutilboutil#!/usr/bin/env ruby # frozen_string_literal: true require 'fileutils' require 'json' require 'netrc' require 'octokit' require 'shellwords' require 'uri' def run(*args) puts(' ' + args.map { |s| Shellwords.escape(s) }.join(' ')) system(*args) end gem_name = 'ddmemoize' version_constant = 'DDMemoize::VERSION' gem_path = 'ddmemoize' puts '=== Logging in to GitHub’s API…' client = Octokit::Client.new(netrc: true) puts puts '=== Deleting old *.gem files…' Dir['*.gem'].each do |fn| puts "deleting #{fn}…" FileUtils.rm_f(fn) end puts puts '=== Verifying presence of release date…' unless File.readlines('NEWS.md').drop(2).first =~ / \(\d{4}-\d{2}-\d{2}\)$/ warn 'No proper release date found!' exit 1 end puts puts '=== Reading version…' require "./lib/#{gem_path}/version" version = eval(version_constant) # rubocop:disable Security/Eval puts "Version = #{version}" puts puts '=== Building new gem…' run('gem', 'build', 'ddmemoize.gemspec') puts puts '=== Verifying that gems were built properly…' gem_filename = "#{gem_name}-#{version}.gem" unless File.file?(gem_filename) warn "Error: Could not find gem: #{gem_filename}" exit 1 end puts puts '=== Verifying that gem version does not yet exist…' url = URI.parse("https://rubygems.org/api/v1/versions/#{gem_name}.json") response = Net::HTTP.get_response(url) existing_versions = case response.code when '404' [] when '200' JSON.parse(response.body).map { |e| e.fetch('number') } else warn "Error: Couldn’t fetch version information for #{gem_name} (status #{response.code})" exit 1 end if existing_versions.include?(version) warn "Error: #{gem_name} v#{version} already exists" exit 1 end puts puts '=== Verifying that release does not yet exist…' releases = client.releases('ddfreyne/ddmemoize') release = releases.find { |r| r.tag_name == DDMemoize::VERSION } if release warn 'Release already exists!' warn 'ABORTED!' exit 1 end puts puts '=== Creating Git tag…' run('git', 'tag', '--sign', '--annotate', DDMemoize::VERSION, '--message', "Version #{DDMemoize::VERSION}") puts puts '=== Pushing Git data…' run('git', 'push', 'origin', '--tags') puts puts '=== Pushing gem…' run('gem', 'push', "ddmemoize-#{DDMemoize::VERSION}.gem") puts puts '=== Reading release notes…' release_notes = File.readlines('NEWS.md') .drop(4) .take_while { |l| l !~ /^## / } .join puts puts '=== Creating release on GitHub…' sleep 3 # Give GitHub some time to detect the new tag is_prerelease = DDMemoize::VERSION =~ /a|b|rc/ || DDMemoize::VERSION =~ /^0/ client.create_release( 'ddfreyne/ddmemoize', DDMemoize::VERSION, prerelease: !is_prerelease.nil?, body: release_notes ) puts puts 'DONE!' ddmemoize-1.0.0/NEWS.md0000644000175000017500000000063513336512126014147 0ustar boutilboutil# DDMemoize news ## 1.0.0 (2018-01-07) (identical to 1.0.0rc1) ## 1.0.0rc1 (2018-01-04) Changes: * Renamed telemetry to metrics ## 1.0.0a3 (2017-12-18) Changes: * Simplified telemetry support ## 1.0.0a2 (2017-12-10) Features: * Added telemetry support (#1) Fixes: * Fixed handling of objects that override `#equal?` (but why would you do that anyway?) (#2) ## 1.0.0a1 (2017-12-02) Initial release. ddmemoize-1.0.0/samples/0000755000175000017500000000000013336512126014511 5ustar boutilboutilddmemoize-1.0.0/samples/fib.rb0000644000175000017500000000045213336512126015577 0ustar boutilboutil# frozen_string_literal: true require 'ddmemoize' DDMemoize.enable_metrics class FibFast DDMemoize.activate(self) memoized def fib(n) case n when 0 0 when 1 1 else fib(n - 1) + fib(n - 2) end end end p FibFast.new.fib(1000) DDMemoize.print_metrics ddmemoize-1.0.0/lib/0000755000175000017500000000000013336512126013613 5ustar boutilboutilddmemoize-1.0.0/lib/ddmemoize.rb0000644000175000017500000000455513336512126016126 0ustar boutilboutil# frozen_string_literal: true require 'ref' require 'ddmetrics' require 'singleton' require_relative 'ddmemoize/version' module DDMemoize class Value attr_reader :value def initialize(value) @value = value end end NONE = Object.new def self.activate(mod) mod.extend(Mixin) end class << self def enable_metrics @metrics_enabled = true end def metrics_enabled? @metrics_enabled end def metrics_counter @_metrics_counter ||= DDMetrics::Counter.new end end def self.print_metrics headers = %w[memoization hit miss %] rows_raw = DDMemoize.metrics_counter.map do |label, count| { name: label.fetch(:method), type: label.fetch(:type), count: count, } end rows = rows_raw.group_by { |r| r[:name] }.map do |name, rows_for_name| rows_by_type = rows_for_name.group_by { |r| r[:type] } num_hit = rows_by_type.fetch(:hit, []).fetch(0, {}).fetch(:count, 0) num_miss = rows_by_type.fetch(:miss, []).fetch(0, {}).fetch(:count, 0) pct = num_hit.to_f / (num_hit + num_miss).to_f [name, num_hit.to_s, num_miss.to_s, "#{format('%3.1f', pct * 100)}%"] end all_rows = [headers] + rows puts DDMetrics::Table.new(all_rows).to_s end module Mixin def memoize(method_name) original_method_name = '__nonmemoized_' + method_name.to_s alias_method original_method_name, method_name instance_cache = Hash.new { |hash, key| hash[key] = {} } full_method_name = "#{self}##{method_name}" define_method(method_name) do |*args| instance_method_cache = instance_cache[self] value = NONE if instance_method_cache.key?(args) object = instance_method_cache[args].object value = object ? object.value : NONE end if DDMemoize.metrics_enabled? if NONE.equal?(value) DDMemoize.metrics_counter.increment(method: full_method_name, type: :miss) else DDMemoize.metrics_counter.increment(method: full_method_name, type: :hit) end end if value.equal?(NONE) send(original_method_name, *args).tap do |r| instance_method_cache[args] = Ref::SoftReference.new(Value.new(r)) end else value end end end alias memoized memoize end end ddmemoize-1.0.0/lib/ddmemoize/0000755000175000017500000000000013336512126015570 5ustar boutilboutilddmemoize-1.0.0/lib/ddmemoize/version.rb0000644000175000017500000000011013336512126017572 0ustar boutilboutil# frozen_string_literal: true module DDMemoize VERSION = '1.0.0' end ddmemoize-1.0.0/spec/0000755000175000017500000000000013336512126013777 5ustar boutilboutilddmemoize-1.0.0/spec/spec_helper.rb0000644000175000017500000000043013336512126016612 0ustar boutilboutil# frozen_string_literal: true require 'simplecov' SimpleCov.start require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov require 'ddmemoize' require 'fuubar' RSpec.configure do |c| c.fuubar_progress_bar_options = { format: '%c/%C |<%b>%i| %p%%', } end ddmemoize-1.0.0/spec/ddmemoize_spec.rb0000644000175000017500000000644413336512126017323 0ustar boutilboutil# frozen_string_literal: true DDMemoize.enable_metrics describe DDMemoize do it 'has a version number' do expect(DDMemoize::VERSION).not_to be nil end class MemoizationSpecSample1 DDMemoize.activate(self) def initialize(value) @value = value end def run(n) @value * 10 + n end memoize :run end class MemoizationSpecSample2 DDMemoize.activate(self) def initialize(value) @value = value end def run(n) @value * 100 + n end memoize :run end class MemoizationSpecUpcaser DDMemoize.activate(self) def run(value) value.upcase end memoize :run end class MemoizationSpecEqual DDMemoize.activate(self) class EqualToEverythingValue def equal?(*) true end end def run EqualToEverythingValue.new end memoize :run end class MemoizationSpecUpcaserInlineSyntax DDMemoize.activate(self) memoized def run(value) value.upcase end end class MemoizationSpecInlineSyntaxReturn DDMemoize.activate(self) class << self attr_reader :sym end def self.record(sym) @sym = sym end record memoized def run; end end class MemoizationSpecWithMetrics DDMemoize.activate(self) def run(value) value.upcase end memoize :run end example do sample1a = MemoizationSpecSample1.new(10) sample1b = MemoizationSpecSample1.new(15) sample2a = MemoizationSpecSample2.new(20) sample2b = MemoizationSpecSample2.new(25) 3.times do expect(sample1a.run(5)).to eq(10 * 10 + 5) expect(sample1b.run(7)).to eq(10 * 15 + 7) expect(sample2a.run(5)).to eq(100 * 20 + 5) expect(sample2b.run(7)).to eq(100 * 25 + 7) end end it 'supports frozen objects' do sample = MemoizationSpecSample1.new(10) sample.freeze sample.run(5) end it 'supports objects that bizarrely override #equal?' do sample = MemoizationSpecEqual.new sample.freeze sample.run sample.run sample.run counter = DDMemoize.metrics_counter expect(counter.get(method: 'MemoizationSpecEqual#run', type: :miss)).to eq(1) expect(counter.get(method: 'MemoizationSpecEqual#run', type: :hit)).to eq(2) end it 'supports memoized def … syntax' do upcaser = MemoizationSpecUpcaserInlineSyntax.new expect(upcaser.run('hi')).to eq('HI') end it 'does not crash on #inspect' do upcaser = MemoizationSpecUpcaser.new 10_000.times do |i| upcaser.run("hello world #{i}") end GC.start GC.start upcaser.inspect end it 'returns method name' do expect(MemoizationSpecInlineSyntaxReturn.sym).to eq(:run) end it 'records metrics' do sample = MemoizationSpecWithMetrics.new sample.run('denis') sample.run('denis') sample.run('defreyne') counter = DDMemoize.metrics_counter expect(counter.get(method: 'MemoizationSpecWithMetrics#run', type: :miss)).to eq(2) expect(counter.get(method: 'MemoizationSpecWithMetrics#run', type: :hit)).to eq(1) end it 'prints recorded metrics' do sample = MemoizationSpecWithMetrics.new sample.run('denis') sample.run('denis') sample.run('defreyne') expect { DDMemoize.print_metrics }.to output(/memoization │ hit\s+miss\s+%/).to_stdout end end ddmemoize-1.0.0/.rubocop.yml0000644000175000017500000000154513336512126015324 0ustar boutilboutil# ----- CONFIGURED ----- AllCops: TargetRubyVersion: 2.3 DisplayCopNames: true Style/TrailingCommaInArguments: EnforcedStyleForMultiline: comma Style/TrailingCommaInLiteral: EnforcedStyleForMultiline: comma Layout/IndentArray: EnforcedStyle: consistent # The documentation lives in the README. Style/Documentation: Enabled: false # ----- DISABLED (metrics) ----- # Cops for metrics are disabled because they should not cause tests to fail. Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false Metrics/BlockNesting: Enabled: false Metrics/ClassLength: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/LineLength: Enabled: false Metrics/MethodLength: Enabled: false Metrics/ModuleLength: Enabled: false Metrics/ParameterLists: Enabled: false Metrics/PerceivedComplexity: Enabled: false ddmemoize-1.0.0/LICENSE.txt0000644000175000017500000000207113336512126014670 0ustar boutilboutilThe MIT License (MIT) Copyright (c) 2017 Denis Defreyne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.