-
-
Save palkan/bf3a796268a9730a095fb26cf7f51410 to your computer and use it in GitHub Desktop.
[ruby-next] Memoized endless method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RubyNext.define_text_rewriter "endless_memoized_def" do | |
parser do | |
def default | |
many( | |
alt( | |
def_memoize, | |
ruby_code | |
) | |
) | |
end | |
def def_memoize | |
seq( | |
string("def ").fmap { |s| s }, | |
many(not_followed_by(memoize_op).bind { regexp(/[a-zA-Z_]+/) }).join, | |
memoize_op.fmap { |s| s }, | |
many(not_followed_by(end_of_line).bind { any_char }).join | |
).fmap do |(defstr, name, _, val)| | |
track! | |
"#{defstr}#{name} = @#{name} ||= #{val}" | |
end | |
end | |
def memoize_op | |
wrap(ws, opt_ws, string("||=")) | |
end | |
def ruby_code | |
any_char | |
end | |
end | |
def safe_rewrite(source) | |
parse(source).then(&:join) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# See https://bugs.ruby-lang.org/issues/20202 | |
class Foo | |
def initialize = @bars = 0 | |
def bar ||= :"memoized_value_#{@bars+=1}" | |
end | |
foo = Foo.new | |
puts foo.bar | |
puts foo.bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment