Cheng
Cheng

Reputation: 4886

Invoke an instance method without specify the instance by Ruby meta programing?

How to design the scope method to let it actually puts row.city?

row.scope do 
  puts city
end

Upvotes: 1

Views: 113

Answers (2)

Phrogz
Phrogz

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

sepp2k
sepp2k

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

Related Questions