Skip to content

Commit 169a9a2

Browse files
committed
Memoize helper method instances with Singleton module
Some helpers, like Rails console's `app`, requires memoization of the helper's ivars. To support it IRB needs to memoize helper method instances as well.
1 parent f9347b1 commit 169a9a2

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

lib/irb/helper_method/base.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1+
require "singleton"
2+
13
module IRB
24
module HelperMethod
35
class Base
6+
include Singleton
7+
48
class << self
59
def description(description = nil)
610
@description = description if description

lib/irb/workspace.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ module HelpersContainer
179179
def self.install_helper_methods
180180
HelperMethod.helper_methods.each do |name, helper_method_class|
181181
define_method name do |*args, **opts, &block|
182-
helper_method_class.new.execute(*args, **opts, &block)
182+
helper_method_class.instance.execute(*args, **opts, &block)
183183
end unless method_defined?(name)
184184
end
185185
end

test/irb/test_helper_method.rb

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,13 +97,38 @@ def execute
9797
RUBY
9898

9999
output = run_ruby_file do
100-
type <<~INPUT
101-
my_helper
102-
INPUT
100+
type "my_helper"
103101
type "exit"
104102
end
105103

106104
assert_include(output, 'Hello from MyHelper')
107105
end
106+
107+
def test_helper_method_instances_are_memoized
108+
write_ruby <<~RUBY
109+
require "irb/helper_method"
110+
111+
class MyHelper < IRB::HelperMethod::Base
112+
description "This is a test helper"
113+
114+
def execute(val)
115+
@val ||= val
116+
end
117+
end
118+
119+
IRB::HelperMethod.register(:my_helper, MyHelper)
120+
121+
binding.irb
122+
RUBY
123+
124+
output = run_ruby_file do
125+
type "my_helper(100)"
126+
type "my_helper(200)"
127+
type "exit"
128+
end
129+
130+
assert_include(output, '=> 100')
131+
assert_not_include(output, '=> 200')
132+
end
108133
end
109134
end

0 commit comments

Comments
 (0)