Refactoring2-5

moduleを使ってSVG描画部分を分離

さてようやくクラスの作成.とその前にrubyにあるmoduleを使う.単なる関数をまとめておく容器と思えばいい.SVGの描画のみを扱っている関数群を取り出して,module SVGにまとめる.まさに"Chunking"よ!

まずはmoduleを作って移していく.refactoringのポリシーに従うなら一個ずつ動作確認しながら動かして!! 慣れてきたら,query-replaceでいっぺんにしちゃってもいい.

どっかで見落としたみたいなんやけど,polylineも変更してます. >|ruby| svg0.rb module SVG

 def self.polyline(points,fill,stroke,stroke_width)
   %Q{<polyline fill="#{fill}" stroke="#{stroke}" stroke-width="#{stroke_width}"
      points = "#{points.join(' ')}" />}
 end
 def self.line(x1,y1,x2,y2,stroke,stroke_width)
   %Q{<line x1="#{x1}" y1="#{y1}" x2="#{x2}" y2="#{y2}"
    stroke="#{stroke}" stroke-width="#{stroke_width}" />}
 end
 def self.rect(cx,cy,width,height,fill,stroke,stroke_width)
   %Q{<rect x="#{cx-2}" y="#{cy-2}"
   width="#{width}" height="#{height}"
   fill="#{fill}" stroke="#{stroke}" stroke-width="#{stroke_width}" />}
 end
 def self.text(cx,cy,msg,font_family,font_size,fill)
   %Q{<text x="#{cx}" y="#{cy}"
   font-family="#{font_family}" font-size="#{font_size}"
   fill="#{fill}" >#{msg}</text>}
 end

end

<

さらにファイルも別にして維持がしやすいようにする. >|ruby| refact後 require 'svg0.rb' NUMBER_OF_TOSSES = 20

def toss

 2 * (rand(2)*2 - 1)

end

def values(n)

 a = [0]
 n.times { a << (toss + a[-1]) }
 a

end

SQ=4 SPARK_COLOR='red' def spark(cx, cy, value)

 %Q{#{SVG.rect(cx-SQ/2,cy-SQ/2,SQ,SQ,'red','none',0)}
   #{SVG.text(cx+6, cy+4, value,"Verdana","9",SPARK_COLOR)}}

end

$tosses = values(NUMBER_OF_TOSSES) points = [] $tosses.each_index { |i| points << "#{i},#{200-$tosses[i]}" }

data = %Q{<svg xmlns="http://www.w3.org/2000/svg"

    xmlns:xlink="http://www.w3.org/1999/xlink" > <!-- x-axis -->
 #{SVG.line(0,200,NUMBER_OF_TOSSES,200,"#999","1")}
 #{SVG.polyline(points,"none","#333","1")}
 #{spark(NUMBER_OF_TOSSES-1, 200-$tosses[-1], $tosses[-1])}

</svg>}

puts data

<

ここまで整理されてくると,何をやっているかがすぐに理解できるようになる. しかし,それだけでなく...

Last modified:2024/04/26 23:03:20
Keyword(s):
References:[Refactoring2] [RubyPrimary]