Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I refactor code that is calling multiple methods on the same object?

Tags:

ruby

I have code like this:

 context = area.window.create_cairo_context

 context.set_source_rgb(0, 0, 0)
 context.set_line_width(0.5)
 context.arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees)
 context.arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees)
 context.arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees)
 context.arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
 context.close_path
 context.stroke_preserve
 context.set_source_rgb(0.7, 1.0, 1.0)
 context.fill

Notice that I'm calling methods on the same object over and over again. Is there someway that Ruby will let me change the current object (self) to context so I can just keep calling these methods with no explicit receiver until I change scope?

Or, to put it simply: There must be some way to not have to type context over and over again!

like image 953
marcusM Avatar asked Jul 21 '26 12:07

marcusM


1 Answers

Use instance_exec or instance_eval

area.window.create_cairo_context.instance_exec do
  set_source_rgb(0, 0, 0)
  set_line_width(0.5)
  arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees)
  arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees)
  arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees)
  arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
  close_path
  stroke_preserve
  set_source_rgb(0.7, 1.0, 1.0)
  fill
end

Just to note: you can omit the parentheses around the arguments. This makes it look more like a configuration setting than writing a code. Ruby on Rails people, which I am not one of, seem to heavily prefer this way.

area.window.create_cairo_context.instance_exec do
  set_source_rgb  0,   0,   0
  set_line_width  0.5
  arc           x+width-radius, y+radius,        radius, -90*degrees, 0*degrees
  arc           x+width-radius, y+height-radius, radius, 0*degrees,   90*degrees
  arc           x+radius,       y+height-radius, radius, 90*degrees,  180*degrees
  arc           x+radius,       y+radius,        radius, 180*degrees, 270*degrees
  close_path
  stroke_preserve
  set_source_rgb  0.7, 1.0, 1.0
  fill
end
like image 105
sawa Avatar answered Jul 23 '26 14:07

sawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!