require 'app/configuration' module RubyAMF module Configuration #set the service path used in all requests # RubyAMF::App::RequestStore.service_path = File.expand_path(RAILS_ROOT) + '/app/controllers' # => CLASS MAPPING CONFIGURATION ClassMappings.register( :actionscript => 'Stock', :ruby => 'Stock', :type => 'active_record', :attributes => ["code", "name"]) end end
上面算是整个文件吧,之后我想在另一个同等级路径文件下要操作这个文件
File.open("rubyamf_config.rb") do |file| while line = file.gets unless line.include?("#") line.scan(//) print line end end file.close end
怎么操作呢,1.不要注释,之后把下面的代码写到一个数组里,如最下面的模式
ClassMappings.register( :actionscript => 'Stock', :ruby => 'Stock', :type => 'active_record', :attributes => ["code", "name"]) #模式: {'ClassMappings.register' => ['actionscript' => 'Stock', 'ruby' => 'Stock', 'type' => 'active_record', 'attributes' => ["code", "name"]]}
ruby操作这些玩意还不会呢!哎!如能回答,另加完我得分,不知道javaeye能不能追加?
[code="ruby"]
content = File.read("rubyamf_config.rb")
result =content.gsub(/#.*$/,"").sub(/ClassMappings.register(\s+(.*?)end/m) do
"{" +
'ClassMappings.register'.inspect +
" => " +
"[" +
eval("{#{$1.sub(/\s+$/,"").chop}}").map{|k,v| k.to_s.inspect + " => " + v.inspect}.join(", ") +
"]" +
"}"
end
File.open("rubyamf_config.rb", "w+"){|f| f.write result.gsub("\"","'")}
[/code]
结果:
[code="ruby"]require 'app/configuration'
module RubyAMF
module Configuration
{'ClassMappings.register' => ['type' => 'active_record', 'attributes' => ['code', 'name'], 'ruby' => 'Stock', 'actionscript' => 'Stock']}
end
[/code]
有一点问题:ruby里hash是无序的,结果中的顺序会有变化。感觉对你这个问题没有什么影响。