27. class Product
def initialize
@title = "My First Ruby Book"
@id = "39t8zfeg"
end
end
template = "<p>Product <%=
@id %> has title <%= @title %>.</p>"
product = Product.new
# TODO use the product details
p ERB.new(template).result
28. class Product
def initialize
@title = "My First Ruby Book"
@id = "39t8zfeg"
end
def print
template = "<p>Product <%=
@id %> has title <%= @title %>.</p>"
puts ERB.new(template).result(binding)
end
end
29. class Product
def initialize
@title = "My First Ruby Book"
@id = "39t8zfeg"
end
def print
template = "<p>Product <%=
@id %> has title <%= @title %>.</p>"
puts ERB.new(template).result(binding)
end
end
30. class Product
def initialize
@title = "My First Ruby Book"
@id = "39t8zfeg"
end
end
31. class Product
def initialize
@title = "My First Ruby Book"
@id = "39t8zfeg"
end
def get_binding
binding
end
end
42. … simpler
process /oo/ do |item|
puts "I am rule /oo/!"
puts "I am processing #{item.inspect}!"
end
43. class Item
attr_reader :identifier
def initialize(identifier)
@identifier = identifier
end
end
44. items = [
Item.new('foo'),
Item.new('foobar'),
Item.new('quxbar'),
Item.new('moo')
]
magically_load_rules
items.each do |item|
magically_process(item)
end
45. class Rule
def initialize(pattern, block)
@pattern = pattern
@block = block
end
def applicable_to?(item)
item.identifier =~ @pattern
end
def apply_to(item)
@block.call(item)
end
end
46. class Application
def initialize
@rules = []
end
def load_rules
rules_content = File.read('Rules')
dsl = DSL.new(@rules)
dsl.instance_eval(rules_content)
end
⋮
47. class Application
def initialize
@rules = []
end
def load_rules
rules_content = File.read('Rules')
dsl = DSL.new(@rules)
dsl.instance_eval(rules_content)
end
⋮
48. class Bob
def initialize
@secret = "abc"
end
end
49. bob = Bob.new
p bob.secret
NoMethodError: undefined method `secret'
for #<Bob:0x574324>
64. class Rule
def initialize(pattern, block)
@pattern = pattern
@block = block
end
def applicable_to?(item)
item.identifier =~ @pattern
end
def apply_to(item)
# original way:
@block.call(item)
end
end
65. class Rule
def initialize(pattern, block)
@pattern = pattern
@block = block
end
def applicable_to?(item)
item.identifier =~ @pattern
end
def apply_to(item)
rule_context = RuleContext.new(item)
rule_context.instance_eval(&@block)
end
end
66. process /oo/ do
puts "I am rule /oo/!"
puts "I am processing #{@item.inspect}!"
end
67. process /oo/ do
puts "I am rule /oo/!"
puts "I am processing #{item.inspect}!"
end
72. ‣ The Ruby Object Model
and Metaprogramming
http://www.pragprog.com/screencasts/v-
dtrubyom/the-ruby-object-model-and-
metaprogramming
‣ How nanocʼs Rules DSL Works
http://stoneship.org/journal/2009/how-
nanocs-rules-dsl-works/