如何重構調用同一對象上多個方法的代碼?

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


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?

注意,我反復調用同一個對象上的方法。有什么方法可以讓Ruby讓我把當前對象(self)改為context,這樣我就可以一直調用這些方法,直到我改變作用域為止?

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

或者,簡單地說:一定有某種方法可以不需要一遍又一遍的輸入上下文!

2 个解决方案

#1


3  

Use instance_exec or instance_eval

使用instance_exec或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.

需要注意的是:可以省略參數周圍的括號。這使得它看起來更像一個配置設置,而不是編寫代碼。Ruby on Rails的人(我不是其中之一)似乎非常喜歡這種方式。

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

#2


3  

Why don't you just implement method chaining? Return yourself from each method call so that you can do something like:

為什么不直接實現方法鏈接呢?從每個方法調用中返回您自己,以便您可以做以下事情:

context.set_source_rgb(0, 0, 0)
       .set_line_width(0.5)
       .arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees)
       .close_path.fill

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/04/01/729d4ed6dcab2c1b9aea89a09f8f64df.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com