Commit a978f227
a978f22747b6Merged
Chris Hasiński <[email protected]> · 6 months ago · 1 file · +1 added
Description
test(instance_eval): add bm_instance_eval covering the lifted block form
Seven sections exercise:
- top-level recv.instance_eval with attr_accessor setters
- multiple sequential instance_eval calls on the same receiver
- methods called inside the block dispatching through self
- instance_eval inside a top-level while
- instance_eval inside a top-level if
- interleaved calls on different objects of different classes
- reassignment to another instance of the same class
Each section's output is checked against CRuby by make test.
Details
- Commit
- a978f22747b6
- Parent
- 0caef283e0b1
test/bm_instance_eval.rbaddedView file
1+
# Test instance_eval { block } block-form lifting.2+
# Each section's output is compared against CRuby by `make test`.3+
4+
class Config5+
attr_accessor :port, :host, :debug6+
7+
def initialize8+
@port = 09+
@host = ""10+
@debug = false11+
end12+
end13+
14+
# ---- 1. Top-level basic form ----15+
cfg = Config.new16+
cfg.instance_eval do17+
self.port = 808018+
self.host = "localhost"19+
self.debug = true20+
end21+
puts cfg.port # 808022+
puts cfg.host # localhost23+
puts cfg.debug # true24+
25+
# ---- 2. Two instance_eval calls in sequence (same object) ----26+
cfg.instance_eval do27+
self.port = 909028+
end29+
puts cfg.port # 909030+
31+
# ---- 3. Methods called inside the block dispatch through self ----32+
class Routes33+
attr_accessor :entries34+
35+
def initialize36+
@entries = "init".split(",") # StrArray hint37+
@entries.pop # start empty38+
end39+
40+
def get(path)41+
@entries.push("GET " + path)42+
end43+
44+
def post(path)45+
@entries.push("POST " + path)46+
end47+
end48+
49+
app = Routes.new50+
app.instance_eval do51+
get("/")52+
get("/about")53+
post("/login")54+
end55+
i = 056+
while i < app.entries.length57+
puts app.entries[i]58+
i = i + 159+
end60+
61+
# ---- 4. instance_eval inside a top-level while loop ----62+
counter = Config.new63+
i = 064+
while i < 365+
counter.instance_eval do66+
self.port = self.port + 167+
end68+
i = i + 169+
end70+
puts counter.port # 371+
72+
# ---- 5. instance_eval inside a top-level if branch ----73+
flag = Config.new74+
cond = 175+
if cond > 076+
flag.instance_eval do77+
self.debug = true78+
end79+
end80+
puts flag.debug # true81+
82+
# ---- 6. Different objects of different classes interleaved ----83+
a = Config.new84+
b = Routes.new85+
a.instance_eval { self.port = 1 }86+
b.instance_eval { get("/x") }87+
a.instance_eval { self.port = 2 }88+
b.instance_eval { post("/y") }89+
puts a.port # 290+
puts b.entries.length # 291+
puts b.entries[0] # GET /x92+
puts b.entries[1] # POST /y93+
94+
# ---- 7. Reassignment to another instance of the same class ----95+
fresh = Config.new96+
fresh.instance_eval { self.port = 11 }97+
puts fresh.port # 1198+
fresh = Config.new99+
fresh.instance_eval { self.port = 22 }100+
puts fresh.port # 22