wwl-websocket-rails 0.7.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (120) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +328 -0
  3. data/Gemfile +27 -0
  4. data/MIT-LICENSE +20 -0
  5. data/README.md +239 -0
  6. data/Rakefile +72 -0
  7. data/bin/thin-socketrails +45 -0
  8. data/lib/assets/javascripts/websocket_rails/abstract_connection.js.coffee +45 -0
  9. data/lib/assets/javascripts/websocket_rails/channel.js.coffee +70 -0
  10. data/lib/assets/javascripts/websocket_rails/event.js.coffee +46 -0
  11. data/lib/assets/javascripts/websocket_rails/http_connection.js.coffee +66 -0
  12. data/lib/assets/javascripts/websocket_rails/main.js +6 -0
  13. data/lib/assets/javascripts/websocket_rails/websocket_connection.js.coffee +29 -0
  14. data/lib/assets/javascripts/websocket_rails/websocket_rails.js.coffee +158 -0
  15. data/lib/config.ru +3 -0
  16. data/lib/generators/websocket_rails/install/install_generator.rb +33 -0
  17. data/lib/generators/websocket_rails/install/templates/events.rb +14 -0
  18. data/lib/generators/websocket_rails/install/templates/websocket_rails.rb +68 -0
  19. data/lib/rails/app/controllers/websocket_rails/delegation_controller.rb +13 -0
  20. data/lib/rails/config/routes.rb +7 -0
  21. data/lib/rails/tasks/websocket_rails.tasks +42 -0
  22. data/lib/spec_helpers/matchers/route_matchers.rb +65 -0
  23. data/lib/spec_helpers/matchers/trigger_matchers.rb +138 -0
  24. data/lib/spec_helpers/spec_helper_event.rb +34 -0
  25. data/lib/websocket-rails.rb +108 -0
  26. data/lib/websocket_rails/base_controller.rb +208 -0
  27. data/lib/websocket_rails/channel.rb +97 -0
  28. data/lib/websocket_rails/channel_manager.rb +55 -0
  29. data/lib/websocket_rails/configuration.rb +177 -0
  30. data/lib/websocket_rails/connection_adapters/http.rb +120 -0
  31. data/lib/websocket_rails/connection_adapters/web_socket.rb +35 -0
  32. data/lib/websocket_rails/connection_adapters.rb +195 -0
  33. data/lib/websocket_rails/connection_manager.rb +119 -0
  34. data/lib/websocket_rails/controller_factory.rb +80 -0
  35. data/lib/websocket_rails/data_store.rb +145 -0
  36. data/lib/websocket_rails/dispatcher.rb +129 -0
  37. data/lib/websocket_rails/engine.rb +26 -0
  38. data/lib/websocket_rails/event.rb +193 -0
  39. data/lib/websocket_rails/event_map.rb +184 -0
  40. data/lib/websocket_rails/event_queue.rb +33 -0
  41. data/lib/websocket_rails/internal_events.rb +37 -0
  42. data/lib/websocket_rails/logging.rb +133 -0
  43. data/lib/websocket_rails/spec_helpers.rb +3 -0
  44. data/lib/websocket_rails/synchronization.rb +178 -0
  45. data/lib/websocket_rails/user_manager.rb +276 -0
  46. data/lib/websocket_rails/version.rb +3 -0
  47. data/spec/dummy/Rakefile +7 -0
  48. data/spec/dummy/app/controllers/application_controller.rb +3 -0
  49. data/spec/dummy/app/controllers/chat_controller.rb +53 -0
  50. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  51. data/spec/dummy/app/models/user.rb +2 -0
  52. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  53. data/spec/dummy/config/application.rb +45 -0
  54. data/spec/dummy/config/boot.rb +10 -0
  55. data/spec/dummy/config/database.yml +22 -0
  56. data/spec/dummy/config/environment.rb +5 -0
  57. data/spec/dummy/config/environments/development.rb +26 -0
  58. data/spec/dummy/config/environments/production.rb +49 -0
  59. data/spec/dummy/config/environments/test.rb +34 -0
  60. data/spec/dummy/config/events.rb +7 -0
  61. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  62. data/spec/dummy/config/initializers/inflections.rb +10 -0
  63. data/spec/dummy/config/initializers/mime_types.rb +5 -0
  64. data/spec/dummy/config/initializers/secret_token.rb +7 -0
  65. data/spec/dummy/config/initializers/session_store.rb +8 -0
  66. data/spec/dummy/config/locales/en.yml +5 -0
  67. data/spec/dummy/config/routes.rb +58 -0
  68. data/spec/dummy/config.ru +4 -0
  69. data/spec/dummy/db/development.sqlite3 +0 -0
  70. data/spec/dummy/db/migrate/20130902222552_create_users.rb +10 -0
  71. data/spec/dummy/db/schema.rb +23 -0
  72. data/spec/dummy/db/test.sqlite3 +0 -0
  73. data/spec/dummy/log/development.log +17 -0
  74. data/spec/dummy/log/production.log +0 -0
  75. data/spec/dummy/log/server.log +0 -0
  76. data/spec/dummy/log/test.log +0 -0
  77. data/spec/dummy/public/404.html +26 -0
  78. data/spec/dummy/public/422.html +26 -0
  79. data/spec/dummy/public/500.html +26 -0
  80. data/spec/dummy/public/favicon.ico +0 -0
  81. data/spec/dummy/public/javascripts/application.js +2 -0
  82. data/spec/dummy/public/javascripts/controls.js +965 -0
  83. data/spec/dummy/public/javascripts/dragdrop.js +974 -0
  84. data/spec/dummy/public/javascripts/effects.js +1123 -0
  85. data/spec/dummy/public/javascripts/prototype.js +6001 -0
  86. data/spec/dummy/public/javascripts/rails.js +202 -0
  87. data/spec/dummy/script/rails +6 -0
  88. data/spec/integration/connection_manager_spec.rb +135 -0
  89. data/spec/javascripts/support/jasmine.yml +52 -0
  90. data/spec/javascripts/support/jasmine_helper.rb +38 -0
  91. data/spec/javascripts/support/vendor/sinon-1.7.1.js +4343 -0
  92. data/spec/javascripts/websocket_rails/channel_spec.coffee +112 -0
  93. data/spec/javascripts/websocket_rails/event_spec.coffee +81 -0
  94. data/spec/javascripts/websocket_rails/helpers.coffee +6 -0
  95. data/spec/javascripts/websocket_rails/websocket_connection_spec.coffee +158 -0
  96. data/spec/javascripts/websocket_rails/websocket_rails_spec.coffee +273 -0
  97. data/spec/spec_helper.rb +41 -0
  98. data/spec/spec_helpers/matchers/route_matchers_spec.rb +109 -0
  99. data/spec/spec_helpers/matchers/trigger_matchers_spec.rb +358 -0
  100. data/spec/spec_helpers/spec_helper_event_spec.rb +66 -0
  101. data/spec/support/helper_methods.rb +42 -0
  102. data/spec/support/mock_web_socket.rb +41 -0
  103. data/spec/unit/base_controller_spec.rb +74 -0
  104. data/spec/unit/channel_manager_spec.rb +58 -0
  105. data/spec/unit/channel_spec.rb +169 -0
  106. data/spec/unit/connection_adapters/http_spec.rb +88 -0
  107. data/spec/unit/connection_adapters/web_socket_spec.rb +30 -0
  108. data/spec/unit/connection_adapters_spec.rb +259 -0
  109. data/spec/unit/connection_manager_spec.rb +148 -0
  110. data/spec/unit/controller_factory_spec.rb +76 -0
  111. data/spec/unit/data_store_spec.rb +106 -0
  112. data/spec/unit/dispatcher_spec.rb +203 -0
  113. data/spec/unit/event_map_spec.rb +120 -0
  114. data/spec/unit/event_queue_spec.rb +36 -0
  115. data/spec/unit/event_spec.rb +181 -0
  116. data/spec/unit/logging_spec.rb +162 -0
  117. data/spec/unit/synchronization_spec.rb +150 -0
  118. data/spec/unit/target_validator_spec.rb +88 -0
  119. data/spec/unit/user_manager_spec.rb +165 -0
  120. metadata +320 -0
@@ -0,0 +1,202 @@
1
+ (function() {
2
+ Ajax.Responders.register({
3
+ onCreate: function(request) {
4
+ var token = $$('meta[name=csrf-token]')[0];
5
+ if (token) {
6
+ if (!request.options.requestHeaders) request.options.requestHeaders = {};
7
+ request.options.requestHeaders['X-CSRF-Token'] = token.readAttribute('content');
8
+ }
9
+ }
10
+ });
11
+
12
+ // Technique from Juriy Zaytsev
13
+ // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
14
+ function isEventSupported(eventName) {
15
+ var el = document.createElement('div');
16
+ eventName = 'on' + eventName;
17
+ var isSupported = (eventName in el);
18
+ if (!isSupported) {
19
+ el.setAttribute(eventName, 'return;');
20
+ isSupported = typeof el[eventName] == 'function';
21
+ }
22
+ el = null;
23
+ return isSupported;
24
+ }
25
+
26
+ function isForm(element) {
27
+ return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM';
28
+ }
29
+
30
+ function isInput(element) {
31
+ if (Object.isElement(element)) {
32
+ var name = element.nodeName.toUpperCase();
33
+ return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA';
34
+ }
35
+ else return false;
36
+ }
37
+
38
+ var submitBubbles = isEventSupported('submit'),
39
+ changeBubbles = isEventSupported('change');
40
+
41
+ if (!submitBubbles || !changeBubbles) {
42
+ // augment the Event.Handler class to observe custom events when needed
43
+ Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
44
+ function(init, element, eventName, selector, callback) {
45
+ init(element, eventName, selector, callback);
46
+ // is the handler being attached to an element that doesn't support this event?
47
+ if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
48
+ (!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
49
+ // "submit" => "emulated:submit"
50
+ this.eventName = 'emulated:' + this.eventName;
51
+ }
52
+ }
53
+ );
54
+ }
55
+
56
+ if (!submitBubbles) {
57
+ // discover forms on the page by observing focus events which always bubble
58
+ document.on('focusin', 'form', function(focusEvent, form) {
59
+ // special handler for the real "submit" event (one-time operation)
60
+ if (!form.retrieve('emulated:submit')) {
61
+ form.on('submit', function(submitEvent) {
62
+ var emulated = form.fire('emulated:submit', submitEvent, true);
63
+ // if custom event received preventDefault, cancel the real one too
64
+ if (emulated.returnValue === false) submitEvent.preventDefault();
65
+ });
66
+ form.store('emulated:submit', true);
67
+ }
68
+ });
69
+ }
70
+
71
+ if (!changeBubbles) {
72
+ // discover form inputs on the page
73
+ document.on('focusin', 'input, select, textarea', function(focusEvent, input) {
74
+ // special handler for real "change" events
75
+ if (!input.retrieve('emulated:change')) {
76
+ input.on('change', function(changeEvent) {
77
+ input.fire('emulated:change', changeEvent, true);
78
+ });
79
+ input.store('emulated:change', true);
80
+ }
81
+ });
82
+ }
83
+
84
+ function handleRemote(element) {
85
+ var method, url, params;
86
+
87
+ var event = element.fire("ajax:before");
88
+ if (event.stopped) return false;
89
+
90
+ if (element.tagName.toLowerCase() === 'form') {
91
+ method = element.readAttribute('method') || 'post';
92
+ url = element.readAttribute('action');
93
+ // serialize the form with respect to the submit button that was pressed
94
+ params = element.serialize({ submit: element.retrieve('rails:submit-button') });
95
+ // clear the pressed submit button information
96
+ element.store('rails:submit-button', null);
97
+ } else {
98
+ method = element.readAttribute('data-method') || 'get';
99
+ url = element.readAttribute('href');
100
+ params = {};
101
+ }
102
+
103
+ new Ajax.Request(url, {
104
+ method: method,
105
+ parameters: params,
106
+ evalScripts: true,
107
+
108
+ onCreate: function(response) { element.fire("ajax:create", response); },
109
+ onComplete: function(response) { element.fire("ajax:complete", response); },
110
+ onSuccess: function(response) { element.fire("ajax:success", response); },
111
+ onFailure: function(response) { element.fire("ajax:failure", response); }
112
+ });
113
+
114
+ element.fire("ajax:after");
115
+ }
116
+
117
+ function insertHiddenField(form, name, value) {
118
+ form.insert(new Element('input', { type: 'hidden', name: name, value: value }));
119
+ }
120
+
121
+ function handleMethod(element) {
122
+ var method = element.readAttribute('data-method'),
123
+ url = element.readAttribute('href'),
124
+ csrf_param = $$('meta[name=csrf-param]')[0],
125
+ csrf_token = $$('meta[name=csrf-token]')[0];
126
+
127
+ var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
128
+ $(element.parentNode).insert(form);
129
+
130
+ if (method !== 'post') {
131
+ insertHiddenField(form, '_method', method);
132
+ }
133
+
134
+ if (csrf_param) {
135
+ insertHiddenField(form, csrf_param.readAttribute('content'), csrf_token.readAttribute('content'));
136
+ }
137
+
138
+ form.submit();
139
+ }
140
+
141
+ function disableFormElements(form) {
142
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
143
+ input.store('rails:original-value', input.getValue());
144
+ input.setValue(input.readAttribute('data-disable-with')).disable();
145
+ });
146
+ }
147
+
148
+ function enableFormElements(form) {
149
+ form.select('input[type=submit][data-disable-with]').each(function(input) {
150
+ input.setValue(input.retrieve('rails:original-value')).enable();
151
+ });
152
+ }
153
+
154
+ function allowAction(element) {
155
+ var message = element.readAttribute('data-confirm');
156
+ return !message || confirm(message);
157
+ }
158
+
159
+ document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) {
160
+ if (!allowAction(link)) {
161
+ event.stop();
162
+ return false;
163
+ }
164
+
165
+ if (link.readAttribute('data-remote')) {
166
+ handleRemote(link);
167
+ event.stop();
168
+ } else if (link.readAttribute('data-method')) {
169
+ handleMethod(link);
170
+ event.stop();
171
+ }
172
+ });
173
+
174
+ document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) {
175
+ // register the pressed submit button
176
+ event.findElement('form').store('rails:submit-button', button.name || false);
177
+ });
178
+
179
+ document.on("submit", function(event) {
180
+ var form = event.findElement();
181
+
182
+ if (!allowAction(form)) {
183
+ event.stop();
184
+ return false;
185
+ }
186
+
187
+ if (form.readAttribute('data-remote')) {
188
+ handleRemote(form);
189
+ event.stop();
190
+ } else {
191
+ disableFormElements(form);
192
+ }
193
+ });
194
+
195
+ document.on('ajax:create', 'form', function(event, form) {
196
+ if (form == event.findElement()) disableFormElements(form);
197
+ });
198
+
199
+ document.on('ajax:complete', 'form', function(event, form) {
200
+ if (form == event.findElement()) enableFormElements(form);
201
+ });
202
+ })();
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
3
+
4
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
5
+ require File.expand_path('../../config/boot', __FILE__)
6
+ require 'rails/commands'
@@ -0,0 +1,135 @@
1
+ require 'spec_helper'
2
+ require 'support/mock_web_socket'
3
+
4
+ module WebsocketRails
5
+ describe ConnectionManager, "integration test" do
6
+
7
+ class ProductController < BaseController
8
+ def update_list; true; end
9
+ end
10
+
11
+ def define_test_events
12
+ WebsocketRails.config.route_block = nil
13
+ WebsocketRails::EventMap.describe do
14
+ subscribe :client_connected, :to => ChatController, :with_method => :new_user
15
+ subscribe :change_username, :to => ChatController, :with_method => :change_username
16
+ subscribe :client_error, :to => ChatController, :with_method => :error_occurred
17
+ subscribe :client_disconnected, :to => ChatController, :with_method => :delete_user
18
+
19
+ subscribe :update_list, :to => ChatController, :with_method => :update_user_list
20
+
21
+ namespace :products do
22
+ subscribe :update_list, :to => ProductController, :with_method => :update_list
23
+ end
24
+ end
25
+ end
26
+
27
+ before(:all) do
28
+ define_test_events
29
+ if defined?(ConnectionAdapters::Test)
30
+ ConnectionAdapters.adapters.delete( ConnectionAdapters::Test )
31
+ end
32
+ end
33
+
34
+ around do |example|
35
+ EM.run do
36
+ example.run
37
+ end
38
+ end
39
+
40
+ after do
41
+ EM.stop
42
+ end
43
+
44
+ shared_examples "an evented rack server" do
45
+ context "new connections" do
46
+ it "should execute the controller action associated with the 'client_connected' event" do
47
+ ChatController.any_instance.should_receive(:new_user)
48
+ @server.call( env )
49
+ end
50
+ end
51
+
52
+ context "active connections" do
53
+ context "new message from client" do
54
+ let(:test_message) { ['change_username',{:user_name => 'Joe User'}] }
55
+ let(:encoded_message) { test_message.to_json }
56
+
57
+ it "should execute the controller action associated with the received event" do
58
+ ChatController.any_instance.should_receive(:change_username)
59
+ @server.call( env )
60
+ socket.on_message( encoded_message )
61
+ end
62
+ end
63
+
64
+ context "new message from client under a namespace" do
65
+ let(:test_message) { ['products.update_list',{:product => 'x-ray-vision'}] }
66
+ let(:encoded_message) { test_message.to_json }
67
+
68
+ it "should execute the controller action under the correct namespace" do
69
+ ChatController.any_instance.should_not_receive(:update_user_list)
70
+ ProductController.any_instance.should_receive(:update_list)
71
+ @server.call( env )
72
+ socket.on_message( encoded_message )
73
+ end
74
+ end
75
+
76
+ context "subscribing to a channel" do
77
+ let(:channel_message) { ['websocket_rails.subscribe',{:data => {:channel => 'test_chan'}}] }
78
+ let(:encoded_channel_message) { channel_message.to_json }
79
+
80
+ it "should subscribe the connection to the correct channel" do
81
+ channel = WebsocketRails[:test_chan]
82
+ @server.call( env )
83
+ channel.should_receive(:subscribe).with(socket)
84
+ socket.on_message encoded_channel_message
85
+ end
86
+ end
87
+
88
+ context "client error" do
89
+ it "should execute the controller action associated with the 'client_error' event" do
90
+ ChatController.any_instance.should_receive(:error_occurred)
91
+ @server.call( env )
92
+ socket.on_error
93
+ end
94
+ end
95
+
96
+ context "client disconnects" do
97
+ it "should execute the controller action associated with the 'client_disconnected' event" do
98
+ ChatController.any_instance.should_receive(:delete_user)
99
+ @server.call( env )
100
+ socket.on_close
101
+ end
102
+
103
+ it "should unsubscribe from channels" do
104
+ channel = WebsocketRails[:test_chan]
105
+ @server.call( env )
106
+ channel.should_receive(:unsubscribe).with(socket)
107
+ socket.on_close
108
+ end
109
+ end
110
+ end
111
+ end
112
+
113
+ context "WebSocket Adapter" do
114
+ let(:socket) { @server.connections.first[1] }
115
+
116
+ before do
117
+ ::Faye::WebSocket.stub(:websocket?).and_return(true)
118
+ @server = ConnectionManager.new
119
+ end
120
+
121
+ it_behaves_like 'an evented rack server'
122
+ end
123
+
124
+ describe "HTTP Adapter" do
125
+ let(:socket) { @server.connections.first[1] }
126
+
127
+ before do
128
+ @server = ConnectionManager.new
129
+ end
130
+
131
+ it_behaves_like 'an evented rack server'
132
+ end
133
+
134
+ end
135
+ end
@@ -0,0 +1,52 @@
1
+ # Return an array of filepaths relative to src_dir to include before jasmine specs.
2
+ # Default: []
3
+ #
4
+ # EXAMPLE:
5
+ #
6
+ # src_files:
7
+ # - lib/source1.js
8
+ # - lib/source2.js
9
+ # - dist/**/*.js
10
+ #
11
+ src_dir: spec/javascripts
12
+ src_files:
13
+ - support/vendor/sinon-1.7.1.js
14
+ - generated/assets/websocket_rails.js
15
+ - generated/assets/event.js
16
+ - generated/assets/abstract_connection.js
17
+ - generated/assets/http_connection.js
18
+ - generated/assets/websocket_connection.js
19
+ - generated/assets/channel.js
20
+ - generated/specs/helpers.js
21
+
22
+ spec_dir: spec/javascripts/generated
23
+ spec_files:
24
+ - specs/event_spec.js
25
+ - specs/websocket_connection_spec.js
26
+ - specs/channel_spec.js
27
+ - specs/websocket_rails_spec.js
28
+
29
+ # stylesheets
30
+ #
31
+ # Return an array of stylesheet filepaths relative to src_dir to include before jasmine specs.
32
+ # Default: []
33
+ #
34
+ # EXAMPLE:
35
+ #
36
+ # stylesheets:
37
+ # - css/style.css
38
+ # - stylesheets/*.css
39
+ #
40
+ stylesheets:
41
+
42
+ # helpers
43
+ #
44
+ # Return an array of filepaths relative to spec_dir to include before jasmine specs.
45
+ # Default: ["helpers/**/*.js"]
46
+ #
47
+ # EXAMPLE:
48
+ #
49
+ # helpers:
50
+ # - helpers/**/*.js
51
+ #
52
+ helpers:
@@ -0,0 +1,38 @@
1
+ #Use this file to set/override Jasmine configuration options
2
+ #You can remove it if you don't need it.
3
+ #This file is loaded *after* jasmine.yml is interpreted.
4
+ #
5
+ #Example: using a different boot file.
6
+ #Jasmine.configure do |config|
7
+ # config.boot_dir = '/absolute/path/to/boot_dir'
8
+ # config.boot_files = lambda { ['/absolute/path/to/boot_dir/file.js'] }
9
+ #end
10
+ #
11
+ require 'coffee-script'
12
+
13
+ puts "Precompiling assets..."
14
+
15
+ root = File.expand_path("../../../../lib/assets/javascripts/websocket_rails", __FILE__)
16
+ destination_dir = File.expand_path("../../../../spec/javascripts/generated/assets", __FILE__)
17
+
18
+ glob = File.expand_path("**/*.js.coffee", root)
19
+
20
+ Dir.glob(glob).each do |srcfile|
21
+ srcfile = Pathname.new(srcfile)
22
+ destfile = srcfile.sub(root, destination_dir).sub(".coffee", "")
23
+ FileUtils.mkdir_p(destfile.dirname)
24
+ File.open(destfile, "w") {|f| f.write(CoffeeScript.compile(File.new(srcfile)))}
25
+ end
26
+ puts "Compiling jasmine coffee scripts into javascript..."
27
+ root = File.expand_path("../../../../spec/javascripts/websocket_rails", __FILE__)
28
+ destination_dir = File.expand_path("../../generated/specs", __FILE__)
29
+
30
+ glob = File.expand_path("**/*.coffee", root)
31
+
32
+ Dir.glob(glob).each do |srcfile|
33
+ srcfile = Pathname.new(srcfile)
34
+ destfile = srcfile.sub(root, destination_dir).sub(".coffee", ".js")
35
+ FileUtils.mkdir_p(destfile.dirname)
36
+ File.open(destfile, "w") {|f| f.write(CoffeeScript.compile(File.new(srcfile)))}
37
+ end
38
+