Simple Blocks in Ruby Classes

Simplify your code and stay DRY by wrapping commonly used commands in a block.

If you ever find your self writing ugly code like this:

db = Database.new
db.open
orders = db.fetch_orders
db.close

It may be worth looking at ruby’s block syntax so you can instead write:

Database.new do |db|
  orders = db.fetch_orders
end

Just check if a block is given inside the initialize method and wrap it with the open and close method calls.

class Database

  def initialize
    if block_given?
      open
        yield self
      close
    end
  end

  def open
  end

  def close
  end

  def fetch_orders
  end
end

Leave a Reply