views:

138

answers:

1

I dont know the correct terminology for what i am asking I tried to google it and couldnt ind anything for the same reason

I am writing a ruby library, and i want to rewite the functions so they work as below as i prefer it for readability (inside a block?)

at the moment i have a function that does this

@dwg = Dwg.new("test.dwg")
@dwg.line([0,0,0],[1,1,0])
@dwg.save

i want to rewrite it so it works like this

Dwg.new("test.dwg") do

   line([0,0,0],[1,1,0])
   save

end

can you outline the way i go about this please

+14  A: 

You can define Dwg's initializer to take a block, and then yield to that block with instance_eval, like so:

class MyClass
  def initialize(name, &block)
    @name = name
    instance_eval &block
  end

  def show_name
    puts 'My name is ' + @name
  end
end

MyClass.new('mud') do
  show_name
end

# >> My name is mud

For more information, see the "Blocks for Interface Simplification" section in the recently Creative-Commons-licensed Chapter 2 of Gregory Brown's excellent Ruby Best Practices book. (Its author and publisher are gradually CCing the entire thing, but you can of course still buy a copy to support the work. The iPhone edition is particularly affordable.)

undees
thanks, perfect!
ADAM
mikej