Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memoize helper method instances with Singleton module #931

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/irb/helper_method/base.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
require "singleton"

module IRB
module HelperMethod
class Base
include Singleton

class << self
def description(description = nil)
@description = description if description
Expand Down
2 changes: 1 addition & 1 deletion lib/irb/workspace.rb
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ module HelpersContainer
def self.install_helper_methods
HelperMethod.helper_methods.each do |name, helper_method_class|
define_method name do |*args, **opts, &block|
helper_method_class.new.execute(*args, **opts, &block)
helper_method_class.instance.execute(*args, **opts, &block)
end unless method_defined?(name)
end
end
Expand Down
31 changes: 28 additions & 3 deletions test/irb/test_helper_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,38 @@ def execute
RUBY

output = run_ruby_file do
type <<~INPUT
my_helper
INPUT
type "my_helper"
type "exit"
end

assert_include(output, 'Hello from MyHelper')
end

def test_helper_method_instances_are_memoized
write_ruby <<~RUBY
require "irb/helper_method"

class MyHelper < IRB::HelperMethod::Base
description "This is a test helper"

def execute(val)
@val ||= val
end
end

IRB::HelperMethod.register(:my_helper, MyHelper)

binding.irb
RUBY

output = run_ruby_file do
type "my_helper(100)"
type "my_helper(200)"
type "exit"
end

assert_include(output, '=> 100')
assert_not_include(output, '=> 200')
end
end
end
Loading