Is it possible not to assign context to lambda?
For example:
class Rule
def get_rule
return lambda {puts name}
end
end
class Person
attr_
Yeah, but be careful with it, this one is really easy to abuse. I would personally be apprehensive of code like this.
class Rule
def get_rule
Proc.new { puts name }
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
instance_eval(&Rule.new.get_rule)
end
end
A bit late to party, but here's an alternate way of doing this by explicitly passing the context to the rule.
class Rule
def get_rule
return lambda{|context| puts context.name}
end
end
class Person
attr_accessor :name
def init_rule
@name = "ruby"
Rule.new.get_rule.call(self)
end
end
Person.new.init_rule
#=> ruby
In the spirit of being really late to the party ;-)
I think the pattern that you are using here is the Strategy pattern. This separates the concerns between the code that changes "rules" and the part that is re-used "person". The other strength of this pattern is that you can change the rules at run-time.
How it could look
class Person
attr_accessor :name
def initialize(&rules)
@name = "ruby"
instance_eval(&rules)
end
end
Person.new do
puts @name
end
=> ruby