昨天發(fā)現(xiàn)了Ruby Watir里的一個小問題,沒有辦法在Text Field里輸入中文。雖然已經(jīng)hack了,但是還是不太爽,G.H.Hardy說:
Beauty is the first
test: there is no permanent place in this world for ugly mathematics.
感動了我好久。現(xiàn)在換個說法:
Beauty is the first
test: there is no permanent place in this world for ugly hack code.
這個問題也不太難出理,ruby作為C的front interface在字符串處理上有很深的C的痕跡,嗯,10年前我還是個C程序員嘛,按照從前的做法區(qū)分ASCII碼。
1 def characters_in(value)
2 index = 0
3 while index < value.length
4 len = value[index] > 128 ? 2 : 1
5 yield value[index, len]
6 index += len
7 end
8 end
把TextField里的doKeyPress改一下:
1 characters_in(value) {|c|
2 sleep @ieController.typingspeed
3 @o.value = @o.value.to_s + c
4 fire_key_events}
搞定!但是還是很丑,直接把別人的code改了,contributing to eclipse里說要contribute不要隨便change別人的代碼。好吧,好在ruby擴展起來也不難:
1 require 'Watir'
2
3 module Watir
4 module Cn
5 class IE <Watir::IE
6 def text_field(how , what=nil)
7 return TextField.new(self, how, what)
8 end
9 end
10
11 class TextField < Watir::TextField
12 def doKeyPress( value )
13 begin
14 maxLength = @o.maxLength
15 if value.length > maxLength
16 value = suppliedValue[0 .. maxLength ]
17 @ieController.log " Supplied string is #{suppliedValue.length} chars, which exceeds the max length (#{maxLength}) of the field. Using value: #{value}"
18 end
19 rescue
20 # probably a text area - so it doesnt have a max Length
21 maxLength = -1
22 end
23
24 Cn.characters_in(value) {|c|
25 sleep @ieController.typingspeed
26 @o.value = @o.value.to_s + c
27 fire_key_events}
28 end
29 end
30
31 def Cn.characters_in(value)
32 index = 0
33 while index < value.length
34 len = value[index] > 128 ? 2 : 1
35 yield value[index, len]
36 index += len
37 end
38 end
39 end
40 end
測試一下:
require 'watir-cn'
ie = Watir::Cn::IE.start('http://www.google.com')
ie.text_field(:name, 'q').set('Ruby Watir 功能測試'
成功。最后一步是貢獻社區(qū),直接登到rubyforge,找到Watir然后submit了兩個patch:一個直接修改watir庫的一個是獨立的watir-cn的。推薦大家使用第二個的patch。地址在:
http://rubyforge.org/tracker/index.php?func=detail&aid=3232&group_id=104&atid=489