public
Fork of kakutani/yaml_waml
Description: Rails plugin to workaround for fixing output result of 'to_yaml' method treats multibyte UTF-8 string(such as japanese) as binary.
Homepage: http://code.google.com/p/yaml-waml/
Clone URL: git://github.com/ohac/yaml_waml.git
yaml_waml / lib / yaml_waml.rb
100644 34 lines (31 sloc) 0.879 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require "yaml"
 
class String
  def is_binary_data?
    false
  end
end
 
ObjectSpace.each_object(Class) do |klass|
  klass.class_eval do
    if method_defined?(:to_yaml) && !method_defined?(:to_yaml_with_decode)
      def to_yaml_with_decode(*args)
        result = to_yaml_without_decode(*args)
        if result.kind_of? String
          # decode for workaround
          result.gsub(/\\x(\w{2})/){
            [Regexp.last_match.captures.first.to_i(16)].pack("C")}
        elsif result.kind_of? StringIO
          str = result.string
          str.gsub!(/\\x(\w{2})/){
            [Regexp.last_match.captures.first.to_i(16)].pack("C")}
          result.rewind
          result.write str
          result
        else
          result
        end
      end
      alias_method :to_yaml_without_decode, :to_yaml
      alias_method :to_yaml, :to_yaml_with_decode
    end
  end
end