B Seven
B Seven

Reputation: 45943

How to wrap methods with before and after in Ruby?

Is there a better way to achieve the following? It seems a little clunky to list the methods as symbols...

This code runs an init before and draw after for each of the 4 methods. The following code works, but is there a more readable or idiomatic way of doing it?

Class DrawMap
  def draw_method_1
    ...
  end

  def draw_method_2
    ...
  end

  def draw_all
    [:draw_method_1, :draw_method_2, :draw_method_3, :draw_method_4].each do |method|
      init_draw
      send method
      @draw.draw
    end
  end

...

The Rails before and after filters would do the same thing, but this is not a Rails app.

Ruby 1.9.3

Upvotes: 2

Views: 1116

Answers (1)

Kyle
Kyle

Reputation: 22258

If you just want to make the code above a little cleaner, you could try this:

def draw_all
  (1..4).each do |n|
    init_draw
    send "draw_method_#{n}"
    @draw.draw 
  end
end

Otherwise, there is a pretty good SO question right here that would really help you out. It involves a little metaprogramming that basically redefines methods and wraps them with some additional code. In your case, you would wrap with init_draw and draw.

Upvotes: 2

Related Questions