Skip to content

Commit 2e7caed

Browse files
committed
feat(examples): add object cycle and runtime eval demos
1 parent 6d77587 commit 2e7caed

File tree

4 files changed

+82
-0
lines changed

4 files changed

+82
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Create ruby example programs for reference cycle and runtime code execution via other program

examples/code_provider.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/usr/bin/env ruby
2+
3+
# Output a Ruby code snippet based on the provided identifier.
4+
# This simulates retrieving code from another program at runtime.
5+
6+
snippet = ARGV.shift.to_s
7+
8+
code = case snippet
9+
when '1'
10+
"puts 'Hello from snippet 1'"
11+
when '2'
12+
"msg = 'hello from snippet 2'; puts msg.upcase"
13+
when '3'
14+
"5.times { |i| print i }; puts"
15+
when '4'
16+
"class DynamicClass; def self.greet; puts 'greet from snippet 4'; end; end; DynamicClass.greet"
17+
else
18+
"puts 'Default snippet'"
19+
end
20+
21+
puts code
22+

examples/reference_cycle.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/usr/bin/env ruby
2+
3+
# Build a simple graph of objects with a reference cycle.
4+
class Node
5+
attr_accessor :name, :neighbors
6+
7+
def initialize(name)
8+
@name = name
9+
@neighbors = []
10+
end
11+
end
12+
13+
a = Node.new('A')
14+
b = Node.new('B')
15+
c = Node.new('C')
16+
17+
a.neighbors << b
18+
b.neighbors << c
19+
c.neighbors << a
20+
21+
puts 'Reference cycle created: A -> B -> C -> A'
22+
puts "A neighbors: #{a.neighbors.map(&:name).join(', ')}"
23+
puts "B neighbors: #{b.neighbors.map(&:name).join(', ')}"
24+
puts "C neighbors: #{c.neighbors.map(&:name).join(', ')}"
25+

examples/runtime_code_execution.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env ruby
2+
3+
# Demonstrate various ways of executing Ruby code obtained from another program.
4+
# The code snippet is produced by `code_provider.rb` based on a command-line
5+
# argument.
6+
7+
require 'rbconfig'
8+
require 'tempfile'
9+
10+
snippet_id = ARGV.shift || '1'
11+
provider = File.expand_path('code_provider.rb', __dir__)
12+
code = `#{RbConfig.ruby} #{provider} #{snippet_id}`
13+
14+
puts "Retrieved code:\n#{code}"
15+
16+
puts '\n[Kernel.eval]'
17+
eval(code)
18+
19+
puts '\n[Binding#eval]'
20+
binding.eval(code)
21+
22+
puts '\n[Object#instance_eval]'
23+
Object.new.instance_eval(code)
24+
25+
puts '\n[Class#class_eval]'
26+
Class.new.class_eval(code)
27+
28+
puts '\n[load from file]'
29+
Tempfile.create(['snippet', '.rb']) do |f|
30+
f.write(code)
31+
f.flush
32+
load f.path
33+
end
34+

0 commit comments

Comments
 (0)