Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite simple ruby function to use a block

I do not know the correct terminology. I tried to google it and could not find anything for that reason.

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

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?

like image 270
ADAM Avatar asked Feb 11 '10 08:02

ADAM


1 Answers

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.)

like image 127
Erin Dees Avatar answered Nov 18 '22 02:11

Erin Dees