Reputation: 4886
How to design the scope method to let it actually puts row.city?
row.scope do
puts city
end
Upvotes: 1
Views: 113
Reputation: 303244
class Object
def scope(&block)
instance_eval(&block)
end
end
Thing = Struct.new(:city)
row = Thing.new "Bryn Athyn"
row.scope{ puts city }
#=> Bryn Athyn
If you don't want to monkey-patch Object, you could alternatively:
module Scopeable
def scope(&block)
instance_eval(&block)
end
end
Thing = Struct.new(:city)
row = Thing.new "Bryn Athyn"
row.extend(Scopeable)
row.scope{ puts city }
#=> Bryn Athyn
Although given this, perhaps easiest is simply:
class Object
alias_method :scope, :instance_eval
end
Or easier yet...just use "instance_eval" instead of "scope" :)
Upvotes: 1
Reputation: 370162
Using instance_eval
:
class RowClass
attr_accessor :city
def scope(&blk)
instance_eval(&blk)
end
end
row = RowClass.new
row.city = "bla"
row.scope do
puts city # prints "bla"
end
Upvotes: 3