Skip to content

Instantly share code, notes, and snippets.

@rogeriochaves
Created April 13, 2021 21:11
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 rogeriochaves/e238e2c5f1b031616ac20863d4af4c65 to your computer and use it in GitHub Desktop.
Save rogeriochaves/e238e2c5f1b031616ac20863d4af4c65 to your computer and use it in GitHub Desktop.
Parse ruby .inspect string to be eval'd
def deinspect(str, level=0)
str.gsub!(/:0x0[^ ]+/, '')
matches = str.match(/<([\w:]+) (.*)>/)
return str unless matches
head = matches[1]
body = matches[2]
hash_content = nil
body.gsub!(/\{.+?\}/) do |_|
hash_content = $~[0]
""
end
level_ = level
prev = ""
body.gsub!(/<(?>[^><]+|\g<0>)*>/) do |_|
level_ += 1
prev += deinspect($~[0], level_)
"x#{level_}"
end
args = []
body.gsub("#", "").gsub(/(@?\w+)=([\w0-9]+|"[^"]*"|\{\})/i) do |_|
args << [ $~[1], $~[2] ]
end
args_new = []
after = ""
args.each do |arg|
if arg[0].include? "@"
arg1 = arg[1]
if hash_content
arg1.gsub!(/\{\}/, hash_content)
end
after += "x#{level}.instance_eval { #{arg[0]} = #{arg1} }\n"
else
args_new << ["#{arg[0]}: #{arg[1]}"]
end
end
args_new = args_new.join ", "
if args.length == 0
args_new = body.gsub("#", "")
end
if hash_content
args_new.gsub!(/\{\}/, hash_content)
end
func = "#{head}.new(#{args_new})"
if head == "URI::HTTPS"
func = "URI.parse(\"#{body}\")"
end
if head == "OAuth::Consumer"
func = "OAuth::Consumer.new('foo', 'bar')"
end
if head == "OAuth::AccessToken"
func = "OAuth::AccessToken.new('')"
end
if head == "Net::HTTPOK"
func = "nil"
end
"#{prev}x#{level} = #{func}\n#{after}"
end
print deinspect(str.split("\n").join(""))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment