Skip to content

Instantly share code, notes, and snippets.

@palkan

palkan/config.rb Secret

Created January 24, 2024 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palkan/bf3a796268a9730a095fb26cf7f51410 to your computer and use it in GitHub Desktop.
Save palkan/bf3a796268a9730a095fb26cf7f51410 to your computer and use it in GitHub Desktop.
[ruby-next] Memoized endless method
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
# 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