Skip to content
This repository
Browse code

Defining force_encoding wrapper in WebSocket class instead of definin…

…g String#force_encoding in Ruby 1.8, to avoid conflict with e.g. json_pure gem.
  • Loading branch information...
commit 47821e8b179f722b82268093d85cc877dd961f35 1 parent 818bc07
Hiroshi Ichikawa authored March 01, 2010

Showing 1 changed file with 10 additions and 37 deletions. Show diff stats Hide diff stats

  1. 47  lib/web_socket.rb
47  lib/web_socket.rb
@@ -6,41 +6,6 @@
6 6
 require "uri"
7 7
 
8 8
 
9  
-if RUBY_VERSION < "1.9.0"
10  
-  
11  
-  class Encoding
12  
-      
13  
-      def self.const_missing(name)
14  
-        return Encoding.new()
15  
-      end
16  
-      
17  
-  end
18  
-  
19  
-  class String
20  
-      
21  
-      def force_encoding(encoding)
22  
-        return self
23  
-      end
24  
-      
25  
-      def ord
26  
-        return self[0]
27  
-      end
28  
-      
29  
-      alias bytesize size
30  
-      
31  
-  end
32  
-  
33  
-  class Integer
34  
-      
35  
-      def ord
36  
-        return self
37  
-      end
38  
-      
39  
-  end
40  
-  
41  
-end
42  
-
43  
-
44 9
 class WebSocket
45 10
     
46 11
     class << self
@@ -135,7 +100,7 @@ def send(data)
135 100
       if !@handshaked
136 101
         raise(WebSocket::Error, "call WebSocket\#handshake first")
137 102
       end
138  
-      data = data.dup().force_encoding("ASCII-8BIT")
  103
+      data = force_encoding(data.dup(), "ASCII-8BIT")
139 104
       write("\x00#{data}\xff")
140 105
       flush()
141 106
     end
@@ -149,7 +114,7 @@ def receive()
149 114
       if !(packet =~ /\A\x00(.*)\xff\z/nm)
150 115
         raise(WebSocket::Error, "input must start with \\x00 and end with \\xff")
151 116
       end
152  
-      return $1.force_encoding("UTF-8")
  117
+      return force_encoding($1, "UTF-8")
153 118
     end
154 119
     
155 120
     def tcp_socket
@@ -211,6 +176,14 @@ def flush()
211 176
       @socket.flush()
212 177
     end
213 178
     
  179
+    def force_encoding(str, encoding)
  180
+      if str.respond_to?(:force_encoding)
  181
+        return str.force_encoding(encoding)
  182
+      else
  183
+        return str
  184
+      end
  185
+    end
  186
+    
214 187
 end
215 188
 
216 189
 

0 notes on commit 47821e8

Please sign in to comment.
Something went wrong with that request. Please try again.