From e51b531ce8437a47f68df5c9c61536eda4cd86fc Mon Sep 17 00:00:00 2001 From: Gaelan Steele Date: Wed, 24 Jun 2015 13:38:43 -0700 Subject: [PATCH] Run rubocop auto-correct. --- Gemfile | 2 - app/volt/tasks/live_query/live_query_pool.rb | 2 +- lib/volt/boot.rb | 1 - lib/volt/cli.rb | 9 +- lib/volt/cli/asset_compile.rb | 17 ++- lib/volt/cli/bundle.rb | 4 +- lib/volt/cli/console.rb | 4 +- lib/volt/cli/generate.rb | 4 +- lib/volt/cli/new_gem.rb | 4 +- lib/volt/controllers/collection_helpers.rb | 3 +- lib/volt/controllers/http_controller.rb | 6 +- .../http_controller/http_cookie_persistor.rb | 2 +- lib/volt/controllers/model_controller.rb | 11 +- lib/volt/controllers/template_helpers.rb | 4 +- lib/volt/data_stores/data_store.rb | 8 +- lib/volt/extra_core/inflector/inflections.rb | 14 +-- lib/volt/extra_core/object.rb | 1 + lib/volt/models/array_model.rb | 19 ++- lib/volt/models/associations.rb | 2 +- lib/volt/models/field_helpers.rb | 10 +- lib/volt/models/model.rb | 10 +- lib/volt/models/model_helpers/dirty.rb | 6 +- .../model_helpers/model_change_helpers.rb | 5 +- .../models/model_helpers/model_helpers.rb | 13 +- lib/volt/models/permissions.rb | 13 +- lib/volt/models/persistors/array_store.rb | 1 - lib/volt/models/persistors/model_store.rb | 2 +- lib/volt/models/persistors/page.rb | 2 +- lib/volt/models/persistors/store.rb | 2 +- lib/volt/models/root_models/root_models.rb | 3 +- lib/volt/models/root_models/store_root.rb | 9 +- lib/volt/models/url.rb | 2 +- lib/volt/models/validations/validations.rb | 6 +- lib/volt/models/validators/type_validator.rb | 2 +- lib/volt/page/bindings/attribute_binding.rb | 78 ++++++------ lib/volt/page/bindings/base_binding.rb | 6 +- lib/volt/page/bindings/event_binding.rb | 14 +-- lib/volt/page/targets/attribute_section.rb | 34 +++--- .../binding_document/component_node.rb | 30 ++--- lib/volt/page/tasks.rb | 12 +- lib/volt/reactive/computation.rb | 3 +- lib/volt/reactive/reactive_array.rb | 2 +- lib/volt/router/routes.rb | 10 +- lib/volt/server.rb | 1 - lib/volt/server/component_templates.rb | 25 +--- lib/volt/server/forking_server.rb | 13 +- .../server/html_parser/attribute_scope.rb | 16 +-- lib/volt/server/html_parser/view_handler.rb | 24 ++-- lib/volt/server/html_parser/view_scope.rb | 70 +++++------ .../server/message_bus/base_message_bus.rb | 8 +- .../server/message_bus/message_encoder.rb | 14 +-- lib/volt/server/message_bus/peer_to_peer.rb | 7 +- .../peer_to_peer/peer_connection.rb | 9 +- .../message_bus/peer_to_peer/peer_server.rb | 43 +++---- .../peer_to_peer/server_tracker.rb | 4 +- .../peer_to_peer/socket_with_timeout.rb | 6 +- .../middleware/default_middleware_stack.rb | 30 ++--- .../server/middleware/middleware_stack.rb | 6 +- lib/volt/server/rack/asset_files.rb | 26 ++-- lib/volt/server/rack/component_paths.rb | 4 +- .../server/rack/http_response_renderer.rb | 4 +- lib/volt/server/rack/keep_alive.rb | 2 +- lib/volt/server/rack/opal_files.rb | 6 +- lib/volt/server/socket_connection_handler.rb | 4 +- .../server/websocket/websocket_handler.rb | 8 +- lib/volt/spec/setup.rb | 6 +- lib/volt/tasks/dispatcher.rb | 8 +- lib/volt/utils/csso_patch.rb | 16 +-- lib/volt/utils/ejson.rb | 14 +-- lib/volt/utils/lifecycle_callbacks.rb | 2 +- lib/volt/utils/promise.rb | 112 +++++++----------- lib/volt/utils/promise_extensions.rb | 19 +-- lib/volt/utils/set_patch.rb | 2 - lib/volt/utils/timers.rb | 2 +- lib/volt/volt/app.rb | 11 +- lib/volt/volt/server_setup/app.rb | 8 +- lib/volt/volt/users.rb | 4 +- .../app/main/controllers/main_controller.rb | 2 +- spec/extra_core/hash_spec.rb | 6 +- spec/integration/bindings_spec.rb | 1 - spec/integration/store_spec.rb | 2 +- spec/integration/todos_spec.rb | 4 +- spec/integration/user_spec.rb | 8 +- spec/models/associations_spec.rb | 15 ++- spec/models/buffer_spec.rb | 4 +- spec/models/field_helpers_spec.rb | 1 - .../model_helpers/model_helpers_spec.rb | 2 +- spec/models/model_spec.rb | 10 +- spec/models/permissions_spec.rb | 2 +- spec/models/persistors/store_spec.rb | 2 +- spec/models/user_spec.rb | 3 - spec/models/validations_spec.rb | 2 - .../validators/block_validations_spec.rb | 11 +- .../validators/format_validator_spec.rb | 4 +- spec/models/validators/type_validator_spec.rb | 2 +- spec/page/bindings/content_binding_spec.rb | 1 - spec/page/bindings/each_binding_spec.rb | 15 ++- spec/page/bindings/if_binding_spec.rb | 4 +- .../view_lookup_for_path_spec.rb | 1 - spec/reactive/computation_spec.rb | 9 +- spec/reactive/eventable_spec.rb | 4 +- spec/reactive/reactive_hash_spec.rb | 2 +- spec/server/component_templates_spec.rb | 8 +- spec/server/html_parser/view_parser_spec.rb | 2 +- .../message_bus/message_encoder_spec.rb | 5 +- .../peer_to_peer/peer_connection_spec.rb | 3 +- .../peer_to_peer/peer_server_spec.rb | 7 +- .../peer_to_peer/socket_with_timeout_spec.rb | 2 +- spec/server/message_bus/peer_to_peer_spec.rb | 3 +- spec/server/middleware/middleware_handler.rb | 2 +- spec/server/rack/http_resource_spec.rb | 3 +- spec/tasks/user_tasks_spec.rb | 14 +-- spec/utils/ejson_spec.rb | 12 +- spec/utils/promise_extensions_spec.rb | 23 ++-- spec/utils/task_argument_filtererer_spec.rb | 5 +- .../component/config/initializers/boot.rb | 2 +- .../app/newgem/config/initializers/boot.rb | 2 +- .../app/main/config/initializers/boot.rb | 2 +- templates/project/app/main/models/user.rb | 1 - volt.gemspec | 1 - 120 files changed, 490 insertions(+), 650 deletions(-) diff --git a/Gemfile b/Gemfile index 84f2e787..8f4cad87 100644 --- a/Gemfile +++ b/Gemfile @@ -10,7 +10,6 @@ gem 'volt-mongo' gem 'rbnacl', require: false gem 'rbnacl-libsodium', require: false - group :development do # For testing the kitchen sink app # Twitter bootstrap @@ -59,5 +58,4 @@ platform :mri do # TODO: Move out of MRI block once jruby 9k is outs gem 'sauce', '~> 3.5.3', require: false gem 'sauce-connect', '~> 3.5.0', require: false - end diff --git a/app/volt/tasks/live_query/live_query_pool.rb b/app/volt/tasks/live_query/live_query_pool.rb index c2b55e69..a5e8ea0e 100644 --- a/app/volt/tasks/live_query/live_query_pool.rb +++ b/app/volt/tasks/live_query/live_query_pool.rb @@ -18,7 +18,7 @@ def lookup(collection, query) super(collection, query) end - def updated_collection(collection, skip_channel, from_message_bus=false) + def updated_collection(collection, skip_channel, from_message_bus = false) # collection = collection.to_sym lookup_all(collection).each do |live_query| live_query.run(skip_channel) diff --git a/lib/volt/boot.rb b/lib/volt/boot.rb index e9120f8a..9a301c6b 100644 --- a/lib/volt/boot.rb +++ b/lib/volt/boot.rb @@ -16,7 +16,6 @@ end require 'volt/volt/app' - module Volt def self.boot(app_path) # Boot the app diff --git a/lib/volt/cli.rb b/lib/volt/cli.rb index 48051536..bc0c2450 100644 --- a/lib/volt/cli.rb +++ b/lib/volt/cli.rb @@ -28,15 +28,14 @@ def new(name) bundle_command('install') end - say "" + say '' say "Your app is now ready in the #{name} directory.", :green - say "" - say "To run your app: " + say '' + say 'To run your app: ' say " cd #{name}" - say " bundle exec volt server" + say ' bundle exec volt server' end - desc 'console', 'run the console on the project in the current directory' def console diff --git a/lib/volt/cli/asset_compile.rb b/lib/volt/cli/asset_compile.rb index 830af45e..d6163811 100644 --- a/lib/volt/cli/asset_compile.rb +++ b/lib/volt/cli/asset_compile.rb @@ -45,7 +45,7 @@ def compile puts 'Write index files' write_index - puts "compiled" + puts 'compiled' end def logical_paths_and_full_paths @@ -54,7 +54,6 @@ def logical_paths_and_full_paths yield(logical_path, full_path.to_s) end - end def write_sprockets @@ -62,9 +61,9 @@ def write_sprockets logical_paths_and_full_paths do |logical_path, full_path| # Only include files that aren't compiled elsewhere, like fonts if !logical_path[/[.](y|css|js|html|erb)$/] && - File.extname(logical_path) != '' && - # opal includes some node modules in the standard lib that we don't need to compile in - (full_path !~ /\/opal/ && full_path !~ /\/stdlib\// && logical_path !~ /^node_js\//) + File.extname(logical_path) != '' && + # opal includes some node modules in the standard lib that we don't need to compile in + (full_path !~ /\/opal/ && full_path !~ /\/stdlib\// && logical_path !~ /^node_js\//) write_sprocket_file(logical_path) end end @@ -85,10 +84,10 @@ def write_sprocket_file(logical_path) begin # Only write out the assets # if logical_path =~ /\/assets\// - content = @opal_files.environment[logical_path].to_s - write_file(path, content) - # end - rescue Sprockets::FileNotFound, SyntaxError => e + content = @opal_files.environment[logical_path].to_s + write_file(path, content) + # end + rescue Sprockets::FileNotFound, SyntaxError => e # ignore end end diff --git a/lib/volt/cli/bundle.rb b/lib/volt/cli/bundle.rb index 3385a81f..eaa3f106 100644 --- a/lib/volt/cli/bundle.rb +++ b/lib/volt/cli/bundle.rb @@ -17,7 +17,7 @@ def bundle_command(command) require 'bundler' Bundler.with_clean_env do - full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}] + full_command = %("#{Gem.ruby}" "#{_bundle_command}" #{command}) if options[:quiet] system(full_command, out: File::NULL) else @@ -26,4 +26,4 @@ def bundle_command(command) end end end -end \ No newline at end of file +end diff --git a/lib/volt/cli/console.rb b/lib/volt/cli/console.rb index fda42035..1b1631d2 100644 --- a/lib/volt/cli/console.rb +++ b/lib/volt/cli/console.rb @@ -36,9 +36,7 @@ def evaluate_ruby(code) result = current_binding.eval(code, Pry.eval_path, Pry.current_line) - if result.is_a?(Promise) - result = result.sync - end + result = result.sync if result.is_a?(Promise) set_last_result(result, code) ensure diff --git a/lib/volt/cli/generate.rb b/lib/volt/cli/generate.rb index 2147c6c3..d96b84de 100644 --- a/lib/volt/cli/generate.rb +++ b/lib/volt/cli/generate.rb @@ -29,8 +29,8 @@ def component(name) lazy_default: [ENV['BUNDLER_EDITOR'], ENV['VISUAL'], ENV['EDITOR']].find { |e| !e.nil? && !e.empty? }, required: false, banner: '/path/to/your/editor', desc: 'Open generated gemspec in the specified editor (defaults to $EDITOR or $BUNDLER_EDITOR)' - method_option :coc, :type => :boolean, :desc => "Generate a code of conduct file. Set a default with `bundle config gem.coc true`." - method_option :mit, :type => :boolean, :desc => "Generate an MIT license file" + method_option :coc, type: :boolean, desc: 'Generate a code of conduct file. Set a default with `bundle config gem.coc true`.' + method_option :mit, type: :boolean, desc: 'Generate an MIT license file' def gem(name) require 'volt/cli/new_gem' diff --git a/lib/volt/cli/new_gem.rb b/lib/volt/cli/new_gem.rb index 1fb49d63..14298ea9 100644 --- a/lib/volt/cli/new_gem.rb +++ b/lib/volt/cli/new_gem.rb @@ -57,7 +57,7 @@ def copy_files end def copy_options - if @options[:coc] or yes?("\nDo you want to include a code of conduct in this gem?\n\n\ + if @options[:coc] || yes?("\nDo you want to include a code of conduct in this gem?\n\n\ Codes of conduct can increase contributions to your project by contributors who \ prefer collaborative, safe spaces. You can read more about the code of conduct at \ contributor-covenant.org. Having a code of conduct means agreeing to the responsibility \ @@ -67,7 +67,7 @@ def copy_options copy('newgem/CODE_OF_CONDUCT.md.tt', 'CODE_OF_CONDUCT.md') end - if @options[:mit] or yes?("\nDo you want to license your code permissively under the MIT license?\n\n\ + if @options[:mit] || yes?("\nDo you want to license your code permissively under the MIT license?\n\n\ This means that any other developer or company will be legally allowed to use your code \ for free as long as they admit you created it. You can read more about the MIT license \ at choosealicense.com/licenses/mit.\n\ny/(n):") diff --git a/lib/volt/controllers/collection_helpers.rb b/lib/volt/controllers/collection_helpers.rb index dd6c5030..abdab592 100644 --- a/lib/volt/controllers/collection_helpers.rb +++ b/lib/volt/controllers/collection_helpers.rb @@ -2,7 +2,6 @@ # @page is expected to be defined and a Volt::Page module Volt module CollectionHelpers - def url_for(params) @page.url.url_for(params) end @@ -15,4 +14,4 @@ def store @page.store end end -end \ No newline at end of file +end diff --git a/lib/volt/controllers/http_controller.rb b/lib/volt/controllers/http_controller.rb index 9c3aef29..687adef1 100644 --- a/lib/volt/controllers/http_controller.rb +++ b/lib/volt/controllers/http_controller.rb @@ -30,7 +30,7 @@ def cookies @cookies ||= Volt::Model.new(request.cookies, persistor: Volt::Persistors::HttpCookiePersistor) end - def perform(action='index') + def perform(action = 'index') filtered = run_callbacks(:before_action, action) send(action.to_sym) unless filtered run_callbacks(:after_action, action) unless filtered @@ -75,9 +75,7 @@ def respond new_cookies = cookies.persistor.changed_cookies new_cookies.each_pair do |key, value| - if value.is_a?(String) - value = {value: value} - end + value = { value: value } if value.is_a?(String) value[:path] = '/' resp.set_cookie(key.to_s, value) diff --git a/lib/volt/controllers/http_controller/http_cookie_persistor.rb b/lib/volt/controllers/http_controller/http_cookie_persistor.rb index 4c1979d2..06f174f9 100644 --- a/lib/volt/controllers/http_controller/http_cookie_persistor.rb +++ b/lib/volt/controllers/http_controller/http_cookie_persistor.rb @@ -19,4 +19,4 @@ def changed(attribute_name) end end end -end \ No newline at end of file +end diff --git a/lib/volt/controllers/model_controller.rb b/lib/volt/controllers/model_controller.rb index d418aedc..b56550d6 100644 --- a/lib/volt/controllers/model_controller.rb +++ b/lib/volt/controllers/model_controller.rb @@ -47,12 +47,10 @@ def first_element node = `nodes[index]` # Return if an element - if `node.nodeType === 1` - return node - end + return node if `node.nodeType === 1` end - return nil + nil end # the u method provides an easy helper to render an unbonud binding. This @@ -60,7 +58,7 @@ def first_element # bound on any model's from a query, the query will not be reactively # listened to. def u - raise "the 'u' method requires a block" unless block_given? + fail "the 'u' method requires a block" unless block_given? Volt::Computation.run_without_tracking { yield } end @@ -134,7 +132,7 @@ def self.new(volt_app, *args, &block) else # Initialize was not called, we should warn since this is probably not # the intended behavior. - Volt.logger.warn("super should be called when creating a custom initialize on class #{inst.class.to_s}") + Volt.logger.warn("super should be called when creating a custom initialize on class #{inst.class}") end inst @@ -159,7 +157,6 @@ def initialize(volt_app, *args) # If a model attribute is passed in, we assign it directly self.model = attrs.locals[:model] if attrs.respond_to?(:model) end - end def go(url) diff --git a/lib/volt/controllers/template_helpers.rb b/lib/volt/controllers/template_helpers.rb index fcffc9f0..9c7e9472 100644 --- a/lib/volt/controllers/template_helpers.rb +++ b/lib/volt/controllers/template_helpers.rb @@ -14,6 +14,4 @@ def self.included(base) base.send :extend, ClassMethods end end - - -end \ No newline at end of file +end diff --git a/lib/volt/data_stores/data_store.rb b/lib/volt/data_stores/data_store.rb index 4e88013b..7999d725 100644 --- a/lib/volt/data_stores/data_store.rb +++ b/lib/volt/data_stores/data_store.rb @@ -14,7 +14,7 @@ def self.fetch adaptor_name = root.const_get(adaptor_name) @adaptor = adaptor_name.new else - raise "#{database_name} is not a supported database, you might be missing a volt-#{database_name} gem" + fail "#{database_name} is not a supported database, you might be missing a volt-#{database_name} gem" end @adaptor @@ -25,10 +25,10 @@ def self.adaptor_client @adaptor_client ||= begin ds_name = Volt.config.public.datastore_name unless ds_name - raise "No data store configured, please include volt-mongo or " + - "another similar gem." + fail 'No data store configured, please include volt-mongo or ' \ + 'another similar gem.' end - adaptor_class_name = ds_name.capitalize + "AdaptorClient" + adaptor_class_name = ds_name.capitalize + 'AdaptorClient' Volt::DataStore.const_get(adaptor_class_name) end end diff --git a/lib/volt/extra_core/inflector/inflections.rb b/lib/volt/extra_core/inflector/inflections.rb index 2a0fcd7c..f503cbb6 100644 --- a/lib/volt/extra_core/inflector/inflections.rb +++ b/lib/volt/extra_core/inflector/inflections.rb @@ -183,13 +183,13 @@ def human(rule, replacement) # clear :plurals def clear(scope = :all) case scope - when :all - @plurals = [] - @singulars = [] - @uncountables = [] - @humans = [] - else - instance_variable_set "@#{scope}", [] + when :all + @plurals = [] + @singulars = [] + @uncountables = [] + @humans = [] + else + instance_variable_set "@#{scope}", [] end end end diff --git a/lib/volt/extra_core/object.rb b/lib/volt/extra_core/object.rb index 35e82381..733f0c57 100644 --- a/lib/volt/extra_core/object.rb +++ b/lib/volt/extra_core/object.rb @@ -38,6 +38,7 @@ def try(*a, &b) end private + def promisify_and_run_method(method_name, &block) promise = Promise.new.resolve(self) diff --git a/lib/volt/models/array_model.rb b/lib/volt/models/array_model.rb index 9c480fa1..7f4eaae7 100644 --- a/lib/volt/models/array_model.rb +++ b/lib/volt/models/array_model.rb @@ -6,7 +6,7 @@ require 'volt/data_stores/data_store' module Volt - class RecordNotFoundException < Exception ; end + class RecordNotFoundException < Exception; end class ArrayModel < ReactiveArray include ModelWrapper @@ -31,7 +31,7 @@ def self.proxy_with_load(*method_names) persistor.try(:root_dep).try(:depend) if persistor.respond_to?(:run_once_loaded) && - !Volt.in_mode?(:no_model_promises) + !Volt.in_mode?(:no_model_promises) persistor.run_once_loaded(block) do send(old_method_name, *args) end @@ -94,9 +94,8 @@ def <<(model) model = wrap_values([model]).first end - if model.is_a?(Model) - if !model.can_create? + unless model.can_create? fail "permissions did not allow create for #{model.inspect}" end @@ -112,8 +111,7 @@ def <<(model) # Mark the model as loaded model.change_state_to(:loaded_state, :loaded) - - end.fail do |err| + end.fail do |err| # remove from the collection because it failed to save on the server # we don't need to call delete on the server. index = @array.index(model) @@ -149,7 +147,7 @@ def append(model) end # Create does append with a default empty model - def create(model={}) + def create(model = {}) append(model) end @@ -203,9 +201,7 @@ def select new_array = [] @array.size.times do |index| value = @array[index] - if yield(value) - new_array << value - end + new_array << value if yield(value) end new_array @@ -281,7 +277,6 @@ def to_json end end - def inspect Computation.run_without_tracking do # Track on size @@ -312,7 +307,7 @@ def fail_not_found_if_nil(promise) if val val else - raise RecordNotFoundException.new + fail RecordNotFoundException.new end end end diff --git a/lib/volt/models/associations.rb b/lib/volt/models/associations.rb index dee7dbbe..2e9fdee7 100644 --- a/lib/volt/models/associations.rb +++ b/lib/volt/models/associations.rb @@ -35,7 +35,7 @@ def has_many(method_name, remote_key_name = nil) # to get the associated model. def has_one(method_name) if method_name.plural? - raise NameError, "has_one takes a singluar association name" + fail NameError, 'has_one takes a singluar association name' end define_method(method_name) do diff --git a/lib/volt/models/field_helpers.rb b/lib/volt/models/field_helpers.rb index deda4686..8fff626e 100644 --- a/lib/volt/models/field_helpers.rb +++ b/lib/volt/models/field_helpers.rb @@ -11,10 +11,8 @@ def field(name, klass = nil) end if klass - # Add type validation, execpt for String, since anything can be a string. - unless klass == String - validate name, type: klass - end + # Add type validation, execpt for String, since anything can be a string. + validate name, type: klass unless klass == String end define_method(name) do @@ -30,9 +28,7 @@ def field(name, klass = nil) elsif klass == Numeric begin orig = val - unless val.is_a?(Numeric) - val = Float(val) - end + val = Float(val) unless val.is_a?(Numeric) if RUBY_PLATFORM == 'opal' # Opal has a bug in 0.7.2 that gives us back NaN without an diff --git a/lib/volt/models/model.rb b/lib/volt/models/model.rb index bb335bfe..dfb6de98 100644 --- a/lib/volt/models/model.rb +++ b/lib/volt/models/model.rb @@ -118,7 +118,7 @@ def id=(val) end def _id - raise "Accessing _id has been deprecated in favor of id" + fail 'Accessing _id has been deprecated in favor of id' end # Return true if the model hasn't been saved yet @@ -314,7 +314,7 @@ def inspect # str += ":#{object_id}" # First, select all of the non-ArrayModel values - attrs = attributes.reject {|key, val| val.is_a?(ArrayModel) }.to_h + attrs = attributes.reject { |key, val| val.is_a?(ArrayModel) }.to_h # Show the :id first, then sort the rest of the attributes id = attrs.delete(:id) @@ -354,6 +354,7 @@ def to_json end private + def run_initial_setup(initial_setup) # Save the changes if initial_setup @@ -375,7 +376,6 @@ def run_initial_setup(initial_setup) end end - # Volt provides a few access methods to get more data about the model, # we want to prevent these from being assigned or accessed through # underscore methods. @@ -411,9 +411,7 @@ def assign_all_attributes(attrs, track_changes = false) end def self.inherited(subclass) - if defined?(RootModels) - RootModels.add_model_class(subclass) - end + RootModels.add_model_class(subclass) if defined?(RootModels) end end diff --git a/lib/volt/models/model_helpers/dirty.rb b/lib/volt/models/model_helpers/dirty.rb index 4b874e7a..8e5c0d42 100644 --- a/lib/volt/models/model_helpers/dirty.rb +++ b/lib/volt/models/model_helpers/dirty.rb @@ -28,11 +28,7 @@ def was(key) # Doing val && val[0] doesn't work in opal # https://github.com/opal/opal/issues/664 - if val - val[0] - else - nil - end + val[0] if val end # Clear changed attributes diff --git a/lib/volt/models/model_helpers/model_change_helpers.rb b/lib/volt/models/model_helpers/model_change_helpers.rb index bffab7db..a0a4a3a4 100644 --- a/lib/volt/models/model_helpers/model_change_helpers.rb +++ b/lib/volt/models/model_helpers/model_change_helpers.rb @@ -48,8 +48,8 @@ def run_changed(attribute_name = nil) self.then end - private + # Should only be called from run_changed. Saves the changes back to the persistor # and clears the tracked changes. def persist_changes(attribute_name) @@ -82,6 +82,5 @@ def persist_changes(attribute_name) result end - end -end \ No newline at end of file +end diff --git a/lib/volt/models/model_helpers/model_helpers.rb b/lib/volt/models/model_helpers/model_helpers.rb index 96391e6d..04712391 100644 --- a/lib/volt/models/model_helpers/model_helpers.rb +++ b/lib/volt/models/model_helpers/model_helpers.rb @@ -31,21 +31,17 @@ def generate_id id.join end - # Return the attributes that are only for this model and any hash sub models # but not any sub-associations. def self_attributes # Don't store any sub-models, those will do their own saving. - attributes.reject { |k, v| v.is_a?(ArrayModel) }.map do |k,v| - if v.is_a?(Model) - v = v.self_attributes - end + attributes.reject { |k, v| v.is_a?(ArrayModel) }.map do |k, v| + v = v.self_attributes if v.is_a?(Model) - [k,v] + [k, v] end.to_h end - # Takes the persistor if there is one and def setup_persistor(persistor) # Use page as the default persistor @@ -69,9 +65,6 @@ def root persistor.try(:root_model) end - - - module ClassMethods # Gets the class for a model at the specified path. def class_at_path(path) diff --git a/lib/volt/models/permissions.rb b/lib/volt/models/permissions.rb index 43bc0ca3..16a929f7 100644 --- a/lib/volt/models/permissions.rb +++ b/lib/volt/models/permissions.rb @@ -9,12 +9,13 @@ module ClassMethods # # @param key [Symbol] the name of the attribute to store def own_by_user(key = :user_id) - relation, pattern = key.to_s, /_id$/ + relation = key.to_s + pattern = /_id$/ if relation.match(pattern) belongs_to key.to_s.gsub(pattern, '') else - raise "You tried to auto associate a model using #{key}, but #{key} "\ - "does not end in `_id`" + fail "You tried to auto associate a model using #{key}, but #{key} "\ + 'does not end in `_id`' end # When the model is created, assign it the user_id (if the user is logged in) on(:new) do # Only assign the user_id if there isn't already one and the user is logged in. @@ -171,10 +172,8 @@ def filtered_attributes end # Deeply filter any nested models - return result.map do |key, value| - if value.is_a?(Model) - value = value.filtered_attributes - end + result.map do |key, value| + value = value.filtered_attributes if value.is_a?(Model) [key, value] end.to_h diff --git a/lib/volt/models/persistors/array_store.rb b/lib/volt/models/persistors/array_store.rb index 5a000322..cc3f4933 100644 --- a/lib/volt/models/persistors/array_store.rb +++ b/lib/volt/models/persistors/array_store.rb @@ -8,7 +8,6 @@ module Persistors class ArrayStore < Store include StoreState - @@query_pool = QueryListenerPool.new attr_reader :model, :root_dep diff --git a/lib/volt/models/persistors/model_store.rb b/lib/volt/models/persistors/model_store.rb index 25837279..ef516302 100644 --- a/lib/volt/models/persistors/model_store.rb +++ b/lib/volt/models/persistors/model_store.rb @@ -126,7 +126,7 @@ def self.changed(model_id, data) if model data.each_pair do |key, value| - model.set(key, value)# if key != :id + model.set(key, value) # if key != :id end end end diff --git a/lib/volt/models/persistors/page.rb b/lib/volt/models/persistors/page.rb index de086f18..21efb830 100644 --- a/lib/volt/models/persistors/page.rb +++ b/lib/volt/models/persistors/page.rb @@ -19,4 +19,4 @@ def where(query) end end end -end \ No newline at end of file +end diff --git a/lib/volt/models/persistors/store.rb b/lib/volt/models/persistors/store.rb index 2cb0b8bb..5aaf881a 100644 --- a/lib/volt/models/persistors/store.rb +++ b/lib/volt/models/persistors/store.rb @@ -27,7 +27,7 @@ def read_new_model(method_name) model = @model.new_array_model([], options) else options[:persistor] = @model.persistor - model= @model.new_model(nil, options) + model = @model.new_model(nil, options) # TODO: Might not need to assign this @model.attributes ||= {} diff --git a/lib/volt/models/root_models/root_models.rb b/lib/volt/models/root_models/root_models.rb index ab0a6d3c..54c25023 100644 --- a/lib/volt/models/root_models/root_models.rb +++ b/lib/volt/models/root_models/root_models.rb @@ -10,7 +10,6 @@ class BaseRootModel < Volt::Model end - ROOT_MODEL_NAMES = [:Store, :Page, :Params, :Cookies, :LocalStore, :Flash] ROOT_MODEL_NAMES.each do |base_name| @@ -23,7 +22,7 @@ class RootModels self.model_classes = [] def self.add_model_class(klass) - self.model_classes << klass + model_classes << klass method_name = klass.to_s.underscore.pluralize diff --git a/lib/volt/models/root_models/store_root.rb b/lib/volt/models/root_models/store_root.rb index 18db1c43..f027fc05 100644 --- a/lib/volt/models/root_models/store_root.rb +++ b/lib/volt/models/root_models/store_root.rb @@ -17,12 +17,11 @@ def model_for_root root end - def get(attr_name, expand = false) res = if attr_name.singular? && attr_name.to_sym != :id - model_for_root.get(attr_name, expand) - else - super + model_for_root.get(attr_name, expand) + else + super end # puts "GOT: #{res.inspect}" @@ -44,4 +43,4 @@ def set(attr_name, value, &block) end end -# StoreRoot.send(:include, Volt::StoreRootHelpers) \ No newline at end of file +# StoreRoot.send(:include, Volt::StoreRootHelpers) diff --git a/lib/volt/models/url.rb b/lib/volt/models/url.rb index d970e31f..5185069d 100644 --- a/lib/volt/models/url.rb +++ b/lib/volt/models/url.rb @@ -163,7 +163,7 @@ def assign_query_hash_to_params fail "no routes match path: #{path}" if new_params == false - return false if new_params == nil + return false if new_params.nil? query_hash.merge!(new_params) diff --git a/lib/volt/models/validations/validations.rb b/lib/volt/models/validations/validations.rb index f3fe047d..88f36f6b 100644 --- a/lib/volt/models/validations/validations.rb +++ b/lib/volt/models/validations/validations.rb @@ -33,7 +33,7 @@ def validate(field_name = nil, options = nil, &block) # context of the block will be the current model. def validations(*run_in_actions, &block) unless block_given? - raise 'validations must take a block, use `validate` to setup a validation on a class directly.' + fail 'validations must take a block, use `validate` to setup a validation on a class directly.' end # Add a validation block to run during each validation @@ -83,9 +83,7 @@ def mark_all_fields! # Look at each validation validations = self.class.validations_to_run - if validations - fields_to_mark += validations.keys - end + fields_to_mark += validations.keys if validations # Also include any current fields fields_to_mark += attributes.keys diff --git a/lib/volt/models/validators/type_validator.rb b/lib/volt/models/validators/type_validator.rb index a4bec7eb..d6f8973b 100644 --- a/lib/volt/models/validators/type_validator.rb +++ b/lib/volt/models/validators/type_validator.rb @@ -11,7 +11,7 @@ def self.validate(model, field_name, args) if args.is_a?(Hash) && args[:message] message = args[:message] else - message = "must be of type #{type_restriction.to_s}" + message = "must be of type #{type_restriction}" end errors[field_name] = [message] diff --git a/lib/volt/page/bindings/attribute_binding.rb b/lib/volt/page/bindings/attribute_binding.rb index 54213426..5855c1bb 100644 --- a/lib/volt/page/bindings/attribute_binding.rb +++ b/lib/volt/page/bindings/attribute_binding.rb @@ -34,27 +34,27 @@ def setup # Bind so when this value updates, we update case @attribute_name - when 'value' - changed_event = Proc.new { changed } - if @is_select - `#{element}.on('change.attrbind', #{changed_event})` - elsif @is_hidden - `#{element}.watch('value', #{changed_event})` - else - `#{element}.on('input.attrbind', #{changed_event})` - end - when 'checked' - changed_event = proc { |event| changed(event) } + when 'value' + changed_event = proc { changed } + if @is_select `#{element}.on('change.attrbind', #{changed_event})` + elsif @is_hidden + `#{element}.watch('value', #{changed_event})` + else + `#{element}.on('input.attrbind', #{changed_event})` + end + when 'checked' + changed_event = proc { |event| changed(event) } + `#{element}.on('change.attrbind', #{changed_event})` end end def changed(event = nil) case @attribute_name - when 'value' - current_value = `#{element}.val() || ''` - else - current_value = `#{element}.is(':checked')` + when 'value' + current_value = `#{element}.val() || ''` + else + current_value = `#{element}.is(':checked')` end if @is_radio @@ -98,21 +98,21 @@ def update(new_value) def value=(val) case @attribute_name - when 'value' - # TODO: only update if its not the same, this keeps it from moving the - # cursor in text fields. - `#{element}.val(#{val})` if val != `(#{element}.val() || '')` - when 'disabled' - # Disabled is handled specially, you can either return a boolean: - # (true being disabled, false not disabled), or you can optionally - # include the "disabled" string. (or any string) - if val != false && val.present? - `#{element}.attr('disabled', 'disabled')` - else - `#{element}.removeAttr('disabled')` - end + when 'value' + # TODO: only update if its not the same, this keeps it from moving the + # cursor in text fields. + `#{element}.val(#{val})` if val != `(#{element}.val() || '')` + when 'disabled' + # Disabled is handled specially, you can either return a boolean: + # (true being disabled, false not disabled), or you can optionally + # include the "disabled" string. (or any string) + if val != false && val.present? + `#{element}.attr('disabled', 'disabled')` else - `#{element}.attr(#{@attribute_name}, #{val})` + `#{element}.removeAttr('disabled')` + end + else + `#{element}.attr(#{@attribute_name}, #{val})` end end @@ -128,16 +128,16 @@ def remove # Unbind events, leave the element there since attribute bindings # aren't responsible for it being there. case @attribute_name - when 'value' - if @is_select - `#{element}.off('change.attrbind')` - elsif @is_hidden - `#{element}.unwatch('value')` - else - `#{element}.off('input.attrbind', #{nil})` - end - when 'checked' - `#{element}.off('change.attrbind', #{nil})` + when 'value' + if @is_select + `#{element}.off('change.attrbind')` + elsif @is_hidden + `#{element}.unwatch('value')` + else + `#{element}.off('input.attrbind', #{nil})` + end + when 'checked' + `#{element}.off('change.attrbind', #{nil})` end if @computation diff --git a/lib/volt/page/bindings/base_binding.rb b/lib/volt/page/bindings/base_binding.rb index 5e00d3c2..dc785b49 100644 --- a/lib/volt/page/bindings/base_binding.rb +++ b/lib/volt/page/bindings/base_binding.rb @@ -44,12 +44,10 @@ def remove_anchors # log out a message about a failed computation or Promise. def getter_fail(error) - message = "#{self.class.to_s} Error: #{error.inspect}" + message = "#{self.class} Error: #{error.inspect}" if RUBY_PLATFORM == 'opal' - if `#{@getter}` - message += "\n" + `#{@getter}.toString()` - end + message += "\n" + `#{@getter}.toString()` if `#{@getter}` else if error.respond_to?(:backtrace) message += "\n" + error.backtrace.join("\n") diff --git a/lib/volt/page/bindings/event_binding.rb b/lib/volt/page/bindings/event_binding.rb index 2933a95e..3d4ed1fc 100644 --- a/lib/volt/page/bindings/event_binding.rb +++ b/lib/volt/page/bindings/event_binding.rb @@ -34,15 +34,14 @@ def initialize(volt_app, target, context, binding_name, event_name, call_proc) # Map blur/focus to focusout/focusin @event_name = case event_name - when 'blur' - 'focusout' - when 'focus' - 'focusin' - else - event_name + when 'blur' + 'focusout' + when 'focus' + 'focusin' + else + event_name end - handler = proc do |js_event| event = JSEvent.new(js_event) event.prevent_default! if event_name == 'submit' @@ -63,7 +62,6 @@ def initialize(volt_app, target, context, binding_name, event_name, call_proc) # Volt.logger.error(err) # end # end - end @listener = page.events.add(@event_name, self, handler) end diff --git a/lib/volt/page/targets/attribute_section.rb b/lib/volt/page/targets/attribute_section.rb index 3f026a43..48deac04 100644 --- a/lib/volt/page/targets/attribute_section.rb +++ b/lib/volt/page/targets/attribute_section.rb @@ -24,7 +24,7 @@ def insert_anchor_before_end(binding_name) component_node = ComponentNode.new(binding_name, end_node, end_node.root || end_node) end_node.insert(-1, component_node) else - raise "can not insert on HtmlNode" + fail 'can not insert on HtmlNode' end end @@ -41,26 +41,26 @@ def rezero_bindings(html, bindings) parts.each do |part| case part - when /\<\!\-\- \$[0-9]+ \-\-\>/ - # Open - binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i - binding = bindings[binding_id] - new_bindings[@@base_binding_id] = binding if binding + when /\<\!\-\- \$[0-9]+ \-\-\>/ + # Open + binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i + binding = bindings[binding_id] + new_bindings[@@base_binding_id] = binding if binding - new_html << "" - id_map[binding_id] = @@base_binding_id - @@base_binding_id += 1 - when /\<\!\-\- \$\/[0-9]+ \-\-\>/ - # Close - binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i - new_html << "" - else - # html string - new_html << part + new_html << "" + id_map[binding_id] = @@base_binding_id + @@base_binding_id += 1 + when /\<\!\-\- \$\/[0-9]+ \-\-\>/ + # Close + binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i + new_html << "" + else + # html string + new_html << part end end - return new_html.join(''), new_bindings + [new_html.join(''), new_bindings] end # Takes in our html and bindings, and rezero's the comment names, and the diff --git a/lib/volt/page/targets/binding_document/component_node.rb b/lib/volt/page/targets/binding_document/component_node.rb index 6b5109d1..d3275d38 100644 --- a/lib/volt/page/targets/binding_document/component_node.rb +++ b/lib/volt/page/targets/binding_document/component_node.rb @@ -40,21 +40,21 @@ def html=(html) parts.each do |part| case part - when /\<\!\-\- \$[0-9]+ \-\-\>/ - # Open - binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i - - sub_node = ComponentNode.new(binding_id, current_node, @root || self) - current_node << sub_node - current_node = sub_node - when /\<\!\-\- \$\/[0-9]+ \-\-\>/ - # Close - # binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i - - current_node = current_node.parent - else - # html string - current_node << HtmlNode.new(part) + when /\<\!\-\- \$[0-9]+ \-\-\>/ + # Open + binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i + + sub_node = ComponentNode.new(binding_id, current_node, @root || self) + current_node << sub_node + current_node = sub_node + when /\<\!\-\- \$\/[0-9]+ \-\-\>/ + # Close + # binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i + + current_node = current_node.parent + else + # html string + current_node << HtmlNode.new(part) end end diff --git a/lib/volt/page/tasks.rb b/lib/volt/page/tasks.rb index c861ae91..b2403502 100644 --- a/lib/volt/page/tasks.rb +++ b/lib/volt/page/tasks.rb @@ -30,12 +30,12 @@ def call(class_name, method_name, meta_data, *args) def received_message(name, promise_id, *args) case name - when 'added', 'removed', 'updated', 'changed' - notify_query(name, *args) - when 'response' - response(promise_id, *args) - when 'reload' - reload + when 'added', 'removed', 'updated', 'changed' + notify_query(name, *args) + when 'response' + response(promise_id, *args) + when 'reload' + reload end end diff --git a/lib/volt/reactive/computation.rb b/lib/volt/reactive/computation.rb index ed9267d1..544aaa3b 100644 --- a/lib/volt/reactive/computation.rb +++ b/lib/volt/reactive/computation.rb @@ -178,7 +178,7 @@ def watch_until!(value, &block) # # Example: # -> { } - def watch_and_resolve!(success, failure=nil, yield_nil_for_unresolved_promise=false) + def watch_and_resolve!(success, failure = nil, yield_nil_for_unresolved_promise = false) # Keep results between runs result = nil @@ -209,7 +209,6 @@ def watch_and_resolve!(success, failure=nil, yield_nil_for_unresolved_promise=fa # Clear result for GC result = nil end - end result.then do |final| diff --git a/lib/volt/reactive/reactive_array.rb b/lib/volt/reactive/reactive_array.rb index b51031b9..1a22eb8f 100644 --- a/lib/volt/reactive/reactive_array.rb +++ b/lib/volt/reactive/reactive_array.rb @@ -122,7 +122,7 @@ def size alias_method :length, :size - def delete_at(index, skip_persistor=false) + def delete_at(index, skip_persistor = false) size = @array.size # Handle a negative index index = size + index if index < 0 diff --git a/lib/volt/router/routes.rb b/lib/volt/router/routes.rb index ec9598f5..f53e71b1 100644 --- a/lib/volt/router/routes.rb +++ b/lib/volt/router/routes.rb @@ -68,7 +68,7 @@ def client(path, params = {}) end # Add server side routes - + def get(path, params) create_route(:get, path, params) end @@ -89,12 +89,12 @@ def delete(path, params) create_route(:delete, path, params) end - #Create rest endpoints + # Create rest endpoints def rest(path, params) endpoints = (params.delete(:only) || [:index, :show, :create, :update, :destroy]).to_a - endpoints = endpoints - params.delete(:except).to_a + endpoints -= params.delete(:except).to_a endpoints.each do |endpoint| - self.send(('restful_' + endpoint.to_s).to_sym, path, params) + send(('restful_' + endpoint.to_s).to_sym, path, params) end end @@ -327,7 +327,7 @@ def has_binding?(string) string.index('{{') && string.index('}}') end - #Append an id to a given path + # Append an id to a given path def path_with_id(base_path) base_path + '/{{ id }}' end diff --git a/lib/volt/server.rb b/lib/volt/server.rb index db5863c9..a783c680 100644 --- a/lib/volt/server.rb +++ b/lib/volt/server.rb @@ -19,7 +19,6 @@ require 'volt/server/forking_server' require 'volt/server/websocket/rack_server_adaptor' - module Volt class Server attr_reader :listener, :app_path diff --git a/lib/volt/server/component_templates.rb b/lib/volt/server/component_templates.rb index 2a77f138..10212bcd 100644 --- a/lib/volt/server/component_templates.rb +++ b/lib/volt/server/component_templates.rb @@ -11,7 +11,6 @@ def call(file_contents) end class ComponentTemplates - module Handlers #:nodoc: # Setup default handler on extend def self.extended(base) @@ -44,7 +43,6 @@ def handler_for_extension(extension) extend ComponentTemplates::Handlers - # client is if we are generating for the client or backend def initialize(component_path, component_name, client = true) @component_path = component_path @@ -57,7 +55,7 @@ def code if @client # On the backend, we just need the views code << generate_controller_code + generate_model_code + - generate_tasks_code + generate_initializers_code + generate_tasks_code + generate_initializers_code end code @@ -80,7 +78,7 @@ def generate_view_code # Load all templates in the folder Dir["#{views_path}*/*.{#{exts.join(',')}}"].sort.each do |view_path| path_parts = view_path.scan(/([^\/]+)\/([^\/]+)\/[^\/]+\/([^\/]+)[.](html|email)$/) - component_name, controller_name, view, _ = path_parts[0] + component_name, controller_name, view, = path_parts[0] # file extension format = File.extname(view_path).downcase.delete('.').to_sym @@ -120,7 +118,6 @@ def generate_view_code end code - end def generate_controller_code @@ -133,22 +130,13 @@ def generate_controller_code implicit_controllers = Dir["#{views_path}*"].sort.map do |path| # remove the /views/ folder and add _controller.rb - path.split('/').tap {|v| v[-2] = 'controllers' }.join('/') + '_controller.rb' + path.split('/').tap { |v| v[-2] = 'controllers' }.join('/') + '_controller.rb' end explicit_controllers = Dir["#{controllers_path}*_controller.rb"].sort controllers = (implicit_controllers + explicit_controllers).uniq controllers.each do |path| - if File.exists?(path) - code << File.read(path) + "\n\n" - else - # parts = path.scan(/([^\/]+)\/controllers\/([^\/]+)_controller[.]rb$/) - # component, controller = parts[0] - - # # Generate a blank controller. (We need to actually generate one so - # # the Template can be attached to it for template inheritance) - # code << "\nmodule #{component.camelize}\n class #{controller.camelize} < Volt::ModelController\n end\nend\n" - end + code << File.read(path) + "\n\n" if File.exist?(path) end code @@ -204,12 +192,11 @@ def generate_initializers_code paths += Dir["#{@component_path}/config/initializers/client/*.rb"] cpath_size = @component_path.size - paths.map! {|path| @component_name + path[cpath_size..-1]} + paths.map! { |path| @component_name + path[cpath_size..-1] } code = "\n" + paths.map { |path| "require '#{path}'" }.join("\n") code end - end -end \ No newline at end of file +end diff --git a/lib/volt/server/forking_server.rb b/lib/volt/server/forking_server.rb index 3c903ac8..42613cb5 100644 --- a/lib/volt/server/forking_server.rb +++ b/lib/volt/server/forking_server.rb @@ -77,7 +77,6 @@ def start_child boot_error(error) end - drb_object = DRb.start_service('drbunix:', [self, @dispatcher]) @writer.puts(drb_object.uri) @@ -98,25 +97,22 @@ def start_child # app to show the user the error and handle reloading requests. def boot_error(error) msg = error.inspect - if error.respond_to?(:backtrace) - msg << "\n" + error.backtrace.join("\n") - end + msg << "\n" + error.backtrace.join("\n") if error.respond_to?(:backtrace) Volt.logger.error(msg) # Only require when needed require 'cgi' - @rack_app = Proc.new do - path = File.join(File.dirname(__FILE__), "forking_server/boot_error.html.erb") + @rack_app = proc do + path = File.join(File.dirname(__FILE__), 'forking_server/boot_error.html.erb') html = File.read(path) error_page = ERB.new(html, nil, '-').result(binding) - [500, {"Content-Type" => "text/html"}, error_page] + [500, { 'Content-Type' => 'text/html' }, error_page] end @dispatcher = ErrorDispatcher.new end - def stop_child # clear the drb object and kill the child process. if @drb_object @@ -205,7 +201,6 @@ def call(env) end end - def reload(changed_files) # only reload the server code if a non-view file was changed server_code_changed = changed_files.any? { |path| File.extname(path) == '.rb' } diff --git a/lib/volt/server/html_parser/attribute_scope.rb b/lib/volt/server/html_parser/attribute_scope.rb index 50bfe0af..4a46fb99 100644 --- a/lib/volt/server/html_parser/attribute_scope.rb +++ b/lib/volt/server/html_parser/attribute_scope.rb @@ -106,15 +106,15 @@ def add_single_attribute(id, attribute_name, parts) def add_multiple_attribute(tag_name, id, attribute_name, parts, content) case attribute_name - when 'checked', 'value' - if parts.size > 1 - if tag_name == 'textarea' - fail "The content of text area's can not be bound to multiple bindings." - else - # Multiple values can not be passed to value or checked attributes. - fail "Multiple bindings can not be passed to a #{attribute_name} binding: #{parts.inspect}" - end + when 'checked', 'value' + if parts.size > 1 + if tag_name == 'textarea' + fail "The content of text area's can not be bound to multiple bindings." + else + # Multiple values can not be passed to value or checked attributes. + fail "Multiple bindings can not be passed to a #{attribute_name} binding: #{parts.inspect}" end + end end string_template_renderer_path = add_string_template_renderer(content) diff --git a/lib/volt/server/html_parser/view_handler.rb b/lib/volt/server/html_parser/view_handler.rb index fb4233fb..10367e31 100644 --- a/lib/volt/server/html_parser/view_handler.rb +++ b/lib/volt/server/html_parser/view_handler.rb @@ -34,21 +34,21 @@ def binding(binding) def start_tag(tag_name, attributes, unary) case tag_name[0] - when ':' - # Component - last.add_component(tag_name, attributes, unary) + when ':' + # Component + last.add_component(tag_name, attributes, unary) + else + if tag_name == 'textarea' + @in_textarea = true + last.add_textarea(tag_name, attributes, unary) else - if tag_name == 'textarea' - @in_textarea = true - last.add_textarea(tag_name, attributes, unary) - else - # Normal tag - attributes = last.process_attributes(tag_name, attributes) - attr_str = last.attribute_string(attributes) + # Normal tag + attributes = last.process_attributes(tag_name, attributes) + attr_str = last.attribute_string(attributes) - last << "<#{tag_name}#{attr_str}#{unary ? ' /' : ''}>" - end + last << "<#{tag_name}#{attr_str}#{unary ? ' /' : ''}>" + end end end diff --git a/lib/volt/server/html_parser/view_scope.rb b/lib/volt/server/html_parser/view_scope.rb index 5d702b21..e07583b1 100644 --- a/lib/volt/server/html_parser/view_scope.rb +++ b/lib/volt/server/html_parser/view_scope.rb @@ -28,45 +28,45 @@ def add_binding(content) args = content[index..-1].strip case first_symbol - when 'if' - add_if(args) - when 'unless' - add_if("!(#{args})") - when 'elsif' - add_else(args) - when 'else' - if args.blank? - add_else(nil) - else - fail "else does not take a conditional, #{content} was provided." - end - when 'view' - add_template(args) - when 'template' - Volt.logger.warn('Deprecation warning: The template binding has been renamed to view. Please update any views accordingly.') - add_template(args) - when 'yield' - add_yield(args) + when 'if' + add_if(args) + when 'unless' + add_if("!(#{args})") + when 'elsif' + add_else(args) + when 'else' + if args.blank? + add_else(nil) + else + fail "else does not take a conditional, #{content} was provided." + end + when 'view' + add_template(args) + when 'template' + Volt.logger.warn('Deprecation warning: The template binding has been renamed to view. Please update any views accordingly.') + add_template(args) + when 'yield' + add_yield(args) + else + if content =~ /.each\s+do\s+\|/ + add_each(content, false) + elsif content =~ /.each_with_index\s+do\s+\|/ + add_each(content, true) else - if content =~ /.each\s+do\s+\|/ - add_each(content, false) - elsif content =~ /.each_with_index\s+do\s+\|/ - add_each(content, true) - else - add_content_binding(content) - end + add_content_binding(content) + end end else case content - when 'end' - # Close the binding - close_scope - when 'else' - add_else(nil) - when 'yield' - add_yield - else - add_content_binding(content) + when 'end' + # Close the binding + close_scope + when 'else' + add_else(nil) + when 'yield' + add_yield + else + add_content_binding(content) end end end diff --git a/lib/volt/server/message_bus/base_message_bus.rb b/lib/volt/server/message_bus/base_message_bus.rb index a05125eb..b318746d 100644 --- a/lib/volt/server/message_bus/base_message_bus.rb +++ b/lib/volt/server/message_bus/base_message_bus.rb @@ -34,19 +34,19 @@ module MessageBus class BaseMessageBus # MessagesBus's should take an instance of a Volt::App def initialize(volt_app) - raise "Not implemented" + fail 'Not implemented' end # Subscribe should return an object that you can call .remove on to stop # the subscription. def subscribe(channel_name, &block) - raise "Not implemented" + fail 'Not implemented' end # publish should push out to all subscribed within the volt cluster. def publish(channel_name, message) - raise "Not implemented" + fail 'Not implemented' end end end -end \ No newline at end of file +end diff --git a/lib/volt/server/message_bus/message_encoder.rb b/lib/volt/server/message_bus/message_encoder.rb index 6ec724b1..39667fb1 100644 --- a/lib/volt/server/message_bus/message_encoder.rb +++ b/lib/volt/server/message_bus/message_encoder.rb @@ -22,7 +22,7 @@ def initialize begin require 'rbnacl/libsodium' rescue LoadError => e - # Ignore, incase they have libsodium installed locally + # Ignore, incase they have libsodium installed locally end begin @@ -60,13 +60,11 @@ def send_message(io, message) end def receive_message(io) - begin - decrypt(Marshal.load(io)) - rescue EOFError => e - # We get EOFError when the connection closes, return nil - nil - end + decrypt(Marshal.load(io)) + rescue EOFError => e + # We get EOFError when the connection closes, return nil + nil end end end -end \ No newline at end of file +end diff --git a/lib/volt/server/message_bus/peer_to_peer.rb b/lib/volt/server/message_bus/peer_to_peer.rb index afcf986f..c2d7108d 100644 --- a/lib/volt/server/message_bus/peer_to_peer.rb +++ b/lib/volt/server/message_bus/peer_to_peer.rb @@ -94,7 +94,7 @@ def start_tracker # Do the initial registration, and wait until its done before connecting # to peers. - @server_tracker.register() + @server_tracker.register end def publish(channel, message) @@ -114,7 +114,7 @@ def publish(channel, message) def peers instances = @page.store._active_volt_instances - instances.where(server_id: {'$ne' => @server_id}).all.sync + instances.where(server_id: { '$ne' => @server_id }).all.sync end def connect_to_peers @@ -199,7 +199,6 @@ def still_alive?(peer_server_id) false end - end end -end \ No newline at end of file +end diff --git a/lib/volt/server/message_bus/peer_to_peer/peer_connection.rb b/lib/volt/server/message_bus/peer_to_peer/peer_connection.rb index 9e1ce3a8..809a8268 100644 --- a/lib/volt/server/message_bus/peer_to_peer/peer_connection.rb +++ b/lib/volt/server/message_bus/peer_to_peer/peer_connection.rb @@ -14,7 +14,7 @@ class PeerConnection # The server id for the connected server attr_reader :peer_server_id, :socket - def initialize(socket, ip, port, message_bus, server=false) + def initialize(socket, ip, port, message_bus, server = false) @message_bus = message_bus @ip = ip @port = port @@ -27,7 +27,6 @@ def initialize(socket, ip, port, message_bus, server=false) # The encoder handles things like formatting and encryption @message_encoder = MessageEncoder.new - failed = false begin if server @@ -102,7 +101,6 @@ def run_worker end end - def listen loop do begin @@ -129,7 +127,6 @@ def listen end end - # Because servers can have many ips, we try the various ip's until we are # able to connect to one. # @param [Array] an array of ip strings @@ -144,7 +141,7 @@ def self.connect_to(message_bus, ips, port) end end - return false + false end private @@ -183,4 +180,4 @@ def reconnect! end end end -end \ No newline at end of file +end diff --git a/lib/volt/server/message_bus/peer_to_peer/peer_server.rb b/lib/volt/server/message_bus/peer_to_peer/peer_server.rb index 718e2f2d..0a964847 100644 --- a/lib/volt/server/message_bus/peer_to_peer/peer_server.rb +++ b/lib/volt/server/message_bus/peer_to_peer/peer_server.rb @@ -6,7 +6,7 @@ module Volt module MessageBus - class NoAvailablePortException < Exception ; end + class NoAvailablePortException < Exception; end class PeerServer def initialize(message_bus) @message_bus = message_bus @@ -31,7 +31,7 @@ def run_server loop do Thread.start(@server.accept) do |socket| peer_connection = PeerConnection.new(socket, nil, nil, - @message_bus, true) + @message_bus, true) @message_bus.add_peer_connection(peer_connection) end @@ -48,31 +48,32 @@ def port end private - def setup_port_ranges - port_ranges = Volt.config.message_bus.try(:bind_port_ranges) - if port_ranges - # Expand any ranges, then sample one from the array - @ports_pool = port_ranges.to_a.map {|v| v.is_a?(Range) ? v.to_a : v }.flatten - else - # port 0, which tells TCPServer to select any random port. - @ports_pool = [0] - end + def setup_port_ranges + port_ranges = Volt.config.message_bus.try(:bind_port_ranges) + + if port_ranges + # Expand any ranges, then sample one from the array + @ports_pool = port_ranges.to_a.map { |v| v.is_a?(Range) ? v.to_a : v }.flatten + else + # port 0, which tells TCPServer to select any random port. + @ports_pool = [0] end + end - def random_port! - port = @ports_pool.sample + def random_port! + port = @ports_pool.sample - unless port - # no available ports left - raise NoAvailablePortException, 'no ports available in Volt.config.message_bus.bind_port_ranges' - end + unless port + # no available ports left + fail NoAvailablePortException, 'no ports available in Volt.config.message_bus.bind_port_ranges' + end - # remove from the pool - @ports_pool.delete(port) + # remove from the pool + @ports_pool.delete(port) - port - end + port + end end end end diff --git a/lib/volt/server/message_bus/peer_to_peer/server_tracker.rb b/lib/volt/server/message_bus/peer_to_peer/server_tracker.rb index 3452dc1c..91dc8795 100644 --- a/lib/volt/server/message_bus/peer_to_peer/server_tracker.rb +++ b/lib/volt/server/message_bus/peer_to_peer/server_tracker.rb @@ -40,7 +40,7 @@ def register if item item.assign_attributes(ips: ips, time: time, port: @port) else - instances << {server_id: @server_id, ips: ips, port: @port, time: time} + instances << { server_id: @server_id, ips: ips, port: @port, time: time } end end end @@ -54,4 +54,4 @@ def local_ips end end end -end \ No newline at end of file +end diff --git a/lib/volt/server/message_bus/peer_to_peer/socket_with_timeout.rb b/lib/volt/server/message_bus/peer_to_peer/socket_with_timeout.rb index e06c3fc0..d0b59514 100644 --- a/lib/volt/server/message_bus/peer_to_peer/socket_with_timeout.rb +++ b/lib/volt/server/message_bus/peer_to_peer/socket_with_timeout.rb @@ -5,7 +5,7 @@ module Volt class SocketWithTimeout - def self.new(host, port, timeout=nil) + def self.new(host, port, timeout = nil) if RUBY_PLATFORM == 'java' TCPSocket.new(host, port) else @@ -15,7 +15,7 @@ def self.new(host, port, timeout=nil) if timeout secs = Integer(timeout) usecs = Integer((timeout - secs) * 1_000_000) - optval = [secs, usecs].pack("l_2") + optval = [secs, usecs].pack('l_2') sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval end @@ -24,4 +24,4 @@ def self.new(host, port, timeout=nil) end end end -end \ No newline at end of file +end diff --git a/lib/volt/server/middleware/default_middleware_stack.rb b/lib/volt/server/middleware/default_middleware_stack.rb index e562a5c4..6afb6909 100644 --- a/lib/volt/server/middleware/default_middleware_stack.rb +++ b/lib/volt/server/middleware/default_middleware_stack.rb @@ -7,8 +7,6 @@ require 'volt/server/rack/index_files' require 'volt/server/rack/http_resource' - - module Volt class DefaultMiddlewareStack # Setup on the middleware we can setup before booting components @@ -24,13 +22,11 @@ def self.preboot_setup(volt_app, rack_app) rack_app.use Rack::ConditionalGet rack_app.use Rack::ETag - rack_app.use Rack::Session::Cookie, { - :key => 'rack.session', - # :domain => 'localhost.com', - :path => '/', - :expire_after => 2592000, - :secret => Volt.config.app_secret - } + rack_app.use Rack::Session::Cookie, key: 'rack.session', + # :domain => 'localhost.com', + path: '/', + expire_after: 2_592_000, + secret: Volt.config.app_secret rack_app.use QuietCommonLogger rack_app.use Rack::ShowExceptions @@ -55,14 +51,14 @@ def self.postboot_setup(volt_app, rack_app) rack_app.use HttpResource, volt_app, volt_app.router rack_app.use Rack::Static, - urls: ['/'], - root: 'config/base', - index: '', - header_rules: [ - [:all, { 'Cache-Control' => 'public, max-age=86400' }] - ] + urls: ['/'], + root: 'config/base', + index: '', + header_rules: [ + [:all, { 'Cache-Control' => 'public, max-age=86400' }] + ] - rack_app.run lambda { |env| [404, { 'Content-Type' => 'text/html; charset=utf-8' }, ['404 - page not found']] } + rack_app.run ->(env) { [404, { 'Content-Type' => 'text/html; charset=utf-8' }, ['404 - page not found']] } end end -end \ No newline at end of file +end diff --git a/lib/volt/server/middleware/middleware_stack.rb b/lib/volt/server/middleware/middleware_stack.rb index 277e0c65..960ae608 100644 --- a/lib/volt/server/middleware/middleware_stack.rb +++ b/lib/volt/server/middleware/middleware_stack.rb @@ -45,11 +45,9 @@ def build end def call(env) - unless @builder - build - end + build unless @builder @builder.call(env) end end -end \ No newline at end of file +end diff --git a/lib/volt/server/rack/asset_files.rb b/lib/volt/server/rack/asset_files.rb index 43ac3e3e..1754d62c 100644 --- a/lib/volt/server/rack/asset_files.rb +++ b/lib/volt/server/rack/asset_files.rb @@ -78,10 +78,10 @@ def javascript_files(opal_files) javascript_files = [] @assets.each do |type, path| case type - when :folder - javascript_files += Dir["#{path}/**/*.js"].sort.map { |folder| '/assets' + folder[path.size..-1] } - when :javascript_file - javascript_files << path + when :folder + javascript_files += Dir["#{path}/**/*.js"].sort.map { |folder| '/assets' + folder[path.size..-1] } + when :javascript_file + javascript_files << path end end @@ -102,15 +102,15 @@ def css_files css_files = [] @assets.each do |type, path| case type - when :folder - # Don't import any css/scss files that start with an underscore, so scss partials - # aren't imported by default: - # http://sass-lang.com/guide - css_files += Dir["#{path}/**/[^_]*.{css,scss}"].sort.map do |folder| - '/assets' + folder[path.size..-1].gsub(/[.]scss$/, '') - end - when :css_file - css_files << path + when :folder + # Don't import any css/scss files that start with an underscore, so scss partials + # aren't imported by default: + # http://sass-lang.com/guide + css_files += Dir["#{path}/**/[^_]*.{css,scss}"].sort.map do |folder| + '/assets' + folder[path.size..-1].gsub(/[.]scss$/, '') + end + when :css_file + css_files << path end end diff --git a/lib/volt/server/rack/component_paths.rb b/lib/volt/server/rack/component_paths.rb index 1b1266dc..e2e962c5 100644 --- a/lib/volt/server/rack/component_paths.rb +++ b/lib/volt/server/rack/component_paths.rb @@ -17,8 +17,8 @@ def app_folders # Gem folders with volt in them # TODO: we should probably qualify this a bit more app_folders += Gem.loaded_specs.values - .select {|gem| gem.name =~ /^volt/ } - .map {|gem| "#{gem.full_gem_path}/app" } + .select { |gem| gem.name =~ /^volt/ } + .map { |gem| "#{gem.full_gem_path}/app" } app_folders.uniq end diff --git a/lib/volt/server/rack/http_response_renderer.rb b/lib/volt/server/rack/http_response_renderer.rb index cd85538b..020f832b 100644 --- a/lib/volt/server/rack/http_response_renderer.rb +++ b/lib/volt/server/rack/http_response_renderer.rb @@ -32,9 +32,7 @@ def render(content) rendered = renderer[:proc].call(to_render) # Unwrap a promise if we got one back - if rendered.is_a?(Promise) - rendered = rendered.sync - end + rendered = rendered.sync if rendered.is_a?(Promise) return [rendered, content.merge(content_type: renderer[:content_type])] end diff --git a/lib/volt/server/rack/keep_alive.rb b/lib/volt/server/rack/keep_alive.rb index 10de4891..6d5a3ff2 100644 --- a/lib/volt/server/rack/keep_alive.rb +++ b/lib/volt/server/rack/keep_alive.rb @@ -17,4 +17,4 @@ def call(env) [status, headers, body] end end -end \ No newline at end of file +end diff --git a/lib/volt/server/rack/opal_files.rb b/lib/volt/server/rack/opal_files.rb index 37aab395..8adbbc9c 100644 --- a/lib/volt/server/rack/opal_files.rb +++ b/lib/volt/server/rack/opal_files.rb @@ -21,9 +21,9 @@ def initialize(builder, app_path, component_paths) # Add the lib directory to the load path Opal.append_path(Volt.root + '/app') - Gem.loaded_specs.values.select {|gem| gem.name =~ /^(volt|ejson_ext)/ } - .each do |gem| - ['app', 'lib'].each do |folder| + Gem.loaded_specs.values.select { |gem| gem.name =~ /^(volt|ejson_ext)/ } + .each do |gem| + %w(app lib).each do |folder| path = gem.full_gem_path + "/#{folder}" Opal.append_path(path) if Dir.exist?(path) diff --git a/lib/volt/server/socket_connection_handler.rb b/lib/volt/server/socket_connection_handler.rb index 97f566b3..600b86f5 100644 --- a/lib/volt/server/socket_connection_handler.rb +++ b/lib/volt/server/socket_connection_handler.rb @@ -9,7 +9,6 @@ class SocketConnectionHandler # This may be changed as new listeners connect, which is fine. attr_accessor :user_id - def initialize(session, *args) @session = session @@ -62,7 +61,6 @@ def send_message(*args) # TODO: Figure out the cause of the issue and submit a fix upstream. EM.next_tick {} end - end def closed @@ -74,7 +72,7 @@ def closed begin @@dispatcher.close_channel(self) rescue DRb::DRbConnError => e - # ignore drb read of @@dispatcher error if child has closed + # ignore drb read of @@dispatcher error if child has closed end else Volt.logger.error("Socket Error: Connection already closed\n#{inspect}") diff --git a/lib/volt/server/websocket/websocket_handler.rb b/lib/volt/server/websocket/websocket_handler.rb index 9800ce3c..e674ac50 100644 --- a/lib/volt/server/websocket/websocket_handler.rb +++ b/lib/volt/server/websocket/websocket_handler.rb @@ -4,10 +4,10 @@ # Load websocket options once at boot # The ENV['DYNO'] option lets it kick in automatically if we're on heroku. WEBSOCKET_OPTIONS = if !ENV['NO_WEBSOCKET_PING'] && - (ENV['WEBSOCKET_PING_TIME'] || ENV['DYNO']) - {ping: (ENV['WEBSOCKET_PING_TIME'] || 30).to_i} -else - {} + (ENV['WEBSOCKET_PING_TIME'] || ENV['DYNO']) + { ping: (ENV['WEBSOCKET_PING_TIME'] || 30).to_i } + else + {} end module Volt diff --git a/lib/volt/spec/setup.rb b/lib/volt/spec/setup.rb index f4e261d5..05e29088 100644 --- a/lib/volt/spec/setup.rb +++ b/lib/volt/spec/setup.rb @@ -29,9 +29,7 @@ def spec_setup(app_path = '.') RSpec.configuration.filter_run_excluding type: :feature end - - - cleanup_db = -> do + cleanup_db = lambda do volt_app.database.drop_database # Clear cached for a reset @@ -79,7 +77,7 @@ def spec_setup(app_path = '.') end # Cleanup after integration tests also. - before(:example, {type: :feature}) do + before(:example, type: :feature) do @__store_accessed = true end end diff --git a/lib/volt/tasks/dispatcher.rb b/lib/volt/tasks/dispatcher.rb index 9861a99b..3ceacfed 100644 --- a/lib/volt/tasks/dispatcher.rb +++ b/lib/volt/tasks/dispatcher.rb @@ -22,9 +22,9 @@ def initialize(volt_app) @worker_pool = Concurrent::ImmediateExecutor.new else @worker_pool = Concurrent::ThreadPoolExecutor.new( - min_threads: Volt.config.min_worker_threads, - max_threads: Volt.config.max_worker_threads - ) + min_threads: Volt.config.min_worker_threads, + max_threads: Volt.config.max_worker_threads + ) end @worker_timeout = Volt.config.worker_timeout || 60 @@ -48,7 +48,6 @@ def dispatch(channel, message) end end - # Check if it is safe to use this method def safe_method?(klass, method_name) # Make sure the class being called is a Task. @@ -133,7 +132,6 @@ def dispatch_in_thread(channel, message) finish.call(error) channel.send_message('response', callback_id, nil, error) end - end end end diff --git a/lib/volt/utils/csso_patch.rb b/lib/volt/utils/csso_patch.rb index 8cfa12c4..2622cd54 100644 --- a/lib/volt/utils/csso_patch.rb +++ b/lib/volt/utils/csso_patch.rb @@ -5,20 +5,16 @@ module Csso class JsLib - def initialize - spec = Gem::Specification.find_by_name("csso-rails") + spec = Gem::Specification.find_by_name('csso-rails') path = spec.gem_dir - lib = File.read(File.expand_path(path + "/" + CSSO_JS_LIB, File.dirname(__FILE__))) - unless @csso = ExecJS.runtime.compile(lib) - raise 'cannot compile or what?' - end + lib = File.read(File.expand_path(path + '/' + CSSO_JS_LIB, File.dirname(__FILE__))) + fail 'cannot compile or what?' unless @csso = ExecJS.runtime.compile(lib) end - def compress css, structural_optimization=true - @csso.call("do_compression", css, !structural_optimization) + def compress(css, structural_optimization = true) + @csso.call('do_compression', css, !structural_optimization) end - end -end \ No newline at end of file +end diff --git a/lib/volt/utils/ejson.rb b/lib/volt/utils/ejson.rb index 746fa544..2ad02a5e 100644 --- a/lib/volt/utils/ejson.rb +++ b/lib/volt/utils/ejson.rb @@ -14,16 +14,14 @@ def self.parse(str) def self.decode(obj) if Array === obj - obj.map {|v| decode(v) } + obj.map { |v| decode(v) } elsif Hash === obj if obj.size == 1 && (escape = obj['$escape']) return escape.map do |key, value| [key, decode(value)] end.to_h elsif obj.size == 1 && (time = obj['$date']) - if time.is_a?(Fixnum) - return Time.at(time / 1000.0) - end + return Time.at(time / 1000.0) if time.is_a?(Fixnum) end obj.map do |key, value| @@ -36,12 +34,12 @@ def self.decode(obj) def self.encode(obj) if Array === obj - obj.map {|v| encode(v) } + obj.map { |v| encode(v) } elsif Hash === obj obj.map do |key, value| if key == '$date' key = '$escape' - value = {'$date' => encode(value)} + value = { '$date' => encode(value) } else value = encode(value) end @@ -50,11 +48,11 @@ def self.encode(obj) end.to_h else if obj.is_a?(Time) - {'$date' => obj.to_i * 1_000} + { '$date' => obj.to_i * 1_000 } else obj end end end end -end \ No newline at end of file +end diff --git a/lib/volt/utils/lifecycle_callbacks.rb b/lib/volt/utils/lifecycle_callbacks.rb index 0a5eac0a..2117783a 100644 --- a/lib/volt/utils/lifecycle_callbacks.rb +++ b/lib/volt/utils/lifecycle_callbacks.rb @@ -56,7 +56,7 @@ def setup_action_helpers_in_class(*callback_names) # To run the callbacks on a class, call #run_callbacks passing in the # callback_name and the action it runs with. If the callback chain was # stopped with #stop_chain, it will return true, otherwise false. - def run_callbacks(callback_name, action=nil) + def run_callbacks(callback_name, action = nil) callbacks = self.class.send(:"#{callback_name}_callbacks") callbacks ||= [] diff --git a/lib/volt/utils/promise.rb b/lib/volt/utils/promise.rb index 86147db1..d23b384b 100644 --- a/lib/volt/utils/promise.rb +++ b/lib/volt/utils/promise.rb @@ -136,7 +136,7 @@ def value end def act? - @action.has_key?(:success) || @action.has_key?(:always) + @action.key?(:success) || @action.key?(:always) end def action @@ -161,7 +161,7 @@ def rejected? def ^(promise) promise << self - self >> promise + self >> promise promise end @@ -180,7 +180,7 @@ def >>(promise) elsif resolved? promise.resolve(@delayed ? @delayed[0] : value) elsif rejected? - if !@action.has_key?(:failure) || Promise === (@delayed ? @delayed[0] : @error) + if !@action.key?(:failure) || Promise === (@delayed ? @delayed[0] : @error) promise.reject(@delayed ? @delayed[0] : error) elsif promise.action.include?(:always) promise.reject(@delayed ? @delayed[0] : error) @@ -191,13 +191,9 @@ def >>(promise) end def resolve(value = nil) - if realized? - raise ArgumentError, 'the promise has already been realized' - end + fail ArgumentError, 'the promise has already been realized' if realized? - if Promise === value - return (value << @prev) ^ self - end + return (value << @prev) ^ self if Promise === value begin if block = @action[:success] || @action[:always] @@ -224,20 +220,16 @@ def resolve!(value) end def reject(value = nil) - if realized? - raise ArgumentError, 'the promise has already been realized' - end + fail ArgumentError, 'the promise has already been realized' if realized? - if Promise === value - return (value << @prev) ^ self - end + return (value << @prev) ^ self if Promise === value begin if block = @action[:failure] || @action[:always] value = block.call(value) end - if @action.has_key?(:always) + if @action.key?(:always) resolve!(value) else reject!(value) @@ -267,41 +259,33 @@ def exception!(error) end def then(&block) - if @next - raise ArgumentError, 'a promise has already been chained' - end + fail ArgumentError, 'a promise has already been chained' if @next self ^ Promise.new(success: block) end - alias do then + alias_method :do, :then def fail(&block) - if @next - raise ArgumentError, 'a promise has already been chained' - end + fail ArgumentError, 'a promise has already been chained' if @next self ^ Promise.new(failure: block) end - alias rescue fail - alias catch fail + alias_method :rescue, :fail + alias_method :catch, :fail def always(&block) - if @next - raise ArgumentError, 'a promise has already been chained' - end + fail ArgumentError, 'a promise has already been chained' if @next self ^ Promise.new(always: block) end - alias finally always - alias ensure always + alias_method :finally, :always + alias_method :ensure, :always def trace(depth = nil, &block) - if @next - raise ArgumentError, 'a promise has already been chained' - end + fail ArgumentError, 'a promise has already been chained' if @next self ^ Trace.new(depth, block) end @@ -309,14 +293,12 @@ def trace(depth = nil, &block) def inspect result = "#<#{self.class}(#{object_id})" - if @next - result += " >> #{@next.inspect}" - end + result += " >> #{@next.inspect}" if @next if realized? result += ": #{(@value || @error).inspect}>" else - result += ">" + result += '>' end result @@ -326,9 +308,7 @@ class Trace < self def self.it(promise) current = [] - if promise.act? || promise.prev.nil? - current.push(promise.value) - end + current.push(promise.value) if promise.act? || promise.prev.nil? if prev = promise.prev current.concat(it(prev)) @@ -340,16 +320,14 @@ def self.it(promise) def initialize(depth, block) @depth = depth - super success: -> { + super success: -> do trace = Trace.it(self).reverse trace.pop - if depth && depth <= trace.length - trace.shift(trace.length - depth) - end + trace.shift(trace.length - depth) if depth && depth <= trace.length block.call(*trace) - } + end end end @@ -359,61 +337,57 @@ def initialize(promises = []) @wait = [] - promises.each {|promise| + promises.each do|promise| wait promise - } + end end def each(&block) - raise ArgumentError, 'no block given' unless block + fail ArgumentError, 'no block given' unless block - self.then {|values| + self.then do|values| values.each(&block) - } + end end def collect(&block) - raise ArgumentError, 'no block given' unless block + fail ArgumentError, 'no block given' unless block - self.then {|values| + self.then do|values| When.new(values.map(&block)) - } + end end def inject(*args, &block) - self.then {|values| + self.then do|values| values.reduce(*args, &block) - } + end end - alias map collect + alias_method :map, :collect - alias reduce inject + alias_method :reduce, :inject def wait(promise) - unless Promise === promise - promise = Promise.value(promise) - end + promise = Promise.value(promise) unless Promise === promise - if promise.act? - promise = promise.then - end + promise = promise.then if promise.act? @wait << promise - promise.always { + promise.always do try if @next - } + end self end - alias and wait + alias_method :and, :wait def >>(*) - super.tap { + super.tap do try - } + end end def try @@ -426,4 +400,4 @@ def try end end end -end \ No newline at end of file +end diff --git a/lib/volt/utils/promise_extensions.rb b/lib/volt/utils/promise_extensions.rb index dcd758db..184df033 100644 --- a/lib/volt/utils/promise_extensions.rb +++ b/lib/volt/utils/promise_extensions.rb @@ -3,7 +3,6 @@ # A temp patch for promises until https://github.com/opal/opal/pull/725 is released. class Promise - # We made a choice not to support comparitors and << and >> on method_missing # on Promises. This makes it easier to understand what promise proxying does # and how it works. It also prevents confusing situations where you try to @@ -27,7 +26,7 @@ def method_missing(method_name, *args, &block) # Allow .each to be called directly on promises def each(&block) - raise ArgumentError, 'no block given' unless block + fail ArgumentError, 'no block given' unless block self.then do |val| val.each(&block) @@ -38,9 +37,7 @@ def each(&block) def inspect result = "#<#{self.class}(#{object_id})" - if @next - result += " >> #{@next.inspect}" - end + result += " >> #{@next.inspect}" if @next if realized? value = value_or_error @@ -55,7 +52,7 @@ def inspect result += ": #{value.inspect}>" else - result += ">" + result += '>' end result @@ -69,9 +66,7 @@ def value_or_error # swallow ExpectationNotMetError's. if defined?(RSpec::Expectations::ExpectationNotMetError) def exception!(error) - if error.is_a?(RSpec::Expectations::ExpectationNotMetError) - raise error - end + fail error if error.is_a?(RSpec::Expectations::ExpectationNotMetError) @exception = true reject!(error) @@ -80,15 +75,13 @@ def exception!(error) # Forward to resolved value def to_json(*args, &block) - self.then {|v| v.to_json(*args, &block) } + self.then { |v| v.to_json(*args, &block) } end - - # Waits for the promise to resolve (assuming it is blocking on # the server) and returns the result. def sync - raise ".sync can only be used on the client" if Volt.client? + fail '.sync can only be used on the client' if Volt.client? result = nil error = nil diff --git a/lib/volt/utils/set_patch.rb b/lib/volt/utils/set_patch.rb index 9fac0377..d66ab975 100644 --- a/lib/volt/utils/set_patch.rb +++ b/lib/volt/utils/set_patch.rb @@ -6,8 +6,6 @@ def delete(o) if include?(o) @hash.delete(o) true - else - nil end end diff --git a/lib/volt/utils/timers.rb b/lib/volt/utils/timers.rb index 51407b87..3cb252e0 100644 --- a/lib/volt/utils/timers.rb +++ b/lib/volt/utils/timers.rb @@ -19,7 +19,7 @@ def self.next_tick(&block) def self.client_set_timeout(interval) if Volt.in_browser? `setTimeout(function() {` - yield + yield `}, interval)` else yield diff --git a/lib/volt/volt/app.rb b/lib/volt/volt/app.rb index c50e751d..98ab2c76 100644 --- a/lib/volt/volt/app.rb +++ b/lib/volt/volt/app.rb @@ -25,9 +25,7 @@ require 'volt/page/tasks' require 'volt/page/page' -unless RUBY_PLATFORM == 'opal' - require 'volt/volt/server_setup/app' -end +require 'volt/volt/server_setup/app' unless RUBY_PLATFORM == 'opal' module Volt class App @@ -41,9 +39,9 @@ class App :middleware attr_accessor :sprockets - def initialize(app_path=nil) + def initialize(app_path = nil) if Volt.server? && !app_path - raise "Volt::App.new requires an app path to boot" + fail 'Volt::App.new requires an app path to boot' end @app_path = app_path @@ -86,7 +84,6 @@ def initialize(app_path=nil) end end - # Setup a Page instance. def setup_page # Run the app config to load all users config files @@ -102,6 +99,6 @@ def setup_page $volt_app = Volt::App.new `$(document).ready(function() {` - $volt_app.page.start + $volt_app.page.start `});` end diff --git a/lib/volt/volt/server_setup/app.rb b/lib/volt/volt/server_setup/app.rb index ef0523d2..9a205300 100644 --- a/lib/volt/volt/server_setup/app.rb +++ b/lib/volt/volt/server_setup/app.rb @@ -25,7 +25,6 @@ def setup_router @router = Routes.new end - def setup_preboot_middleware @middleware = MiddlewareStack.new DefaultMiddlewareStack.preboot_setup(self, @middleware) @@ -49,7 +48,7 @@ def require_http_controllers # This config needs to run earlier than others def run_config path = "#{Volt.root}/config/app.rb" - require(path) if File.exists?(path) + require(path) if File.exist?(path) end # Load in all .rb files in the initializers folders and the config/app.rb @@ -72,7 +71,6 @@ def run_app_and_initializers end end - def reset_query_pool! if RUBY_PLATFORM != 'opal' # The load path isn't setup at the top of app.rb, so we wait to require @@ -100,7 +98,7 @@ def start_message_bus message_bus_class = MessageBus.const_get(bus_name.camelize) rescue NameError => e raise "message bus name #{bus_name} was not found, be sure its " - + "gem is included in the gemfile." + + 'gem is included in the gemfile.' end @message_bus = message_bus_class.new(self) @@ -118,4 +116,4 @@ def start_message_bus end end end -end \ No newline at end of file +end diff --git a/lib/volt/volt/users.rb b/lib/volt/volt/users.rb index d7790707..600a7002 100644 --- a/lib/volt/volt/users.rb +++ b/lib/volt/volt/users.rb @@ -98,7 +98,7 @@ def user end def fetch_current_user - Volt.logger.warn("Deprication Warning: fetch current user have been depricated, Volt.current_user returns a promise now.") + Volt.logger.warn('Deprication Warning: fetch current user have been depricated, Volt.current_user returns a promise now.') current_user end @@ -135,8 +135,8 @@ def user_id_signature user_id_signature end - private + unless RUBY_PLATFORM == 'opal' def salty_user_id(user_id) "#{Volt.config.app_secret}::#{user_id}" diff --git a/spec/apps/kitchen_sink/app/main/controllers/main_controller.rb b/spec/apps/kitchen_sink/app/main/controllers/main_controller.rb index dd70b996..91b8944f 100644 --- a/spec/apps/kitchen_sink/app/main/controllers/main_controller.rb +++ b/spec/apps/kitchen_sink/app/main/controllers/main_controller.rb @@ -13,7 +13,7 @@ def index end def store_demo - puts "STORE DEMO" + puts 'STORE DEMO' end def form_ready diff --git a/spec/extra_core/hash_spec.rb b/spec/extra_core/hash_spec.rb index 80fd1a8b..107b420c 100644 --- a/spec/extra_core/hash_spec.rb +++ b/spec/extra_core/hash_spec.rb @@ -2,8 +2,8 @@ describe Hash do it 'should return a hash without the speicified keys' do - a = {one: 1, two: 2, three: 3} + a = { one: 1, two: 2, three: 3 } - expect(a.without(:one, :three)).to eq({two: 2}) + expect(a.without(:one, :three)).to eq(two: 2) end -end \ No newline at end of file +end diff --git a/spec/integration/bindings_spec.rb b/spec/integration/bindings_spec.rb index 1e81b350..d613411f 100644 --- a/spec/integration/bindings_spec.rb +++ b/spec/integration/bindings_spec.rb @@ -214,7 +214,6 @@ end end - describe 'if/unless binding' do it 'should show corret text' do visit '/' diff --git a/spec/integration/store_spec.rb b/spec/integration/store_spec.rb index 4fa1bedb..9ce57a62 100644 --- a/spec/integration/store_spec.rb +++ b/spec/integration/store_spec.rb @@ -7,4 +7,4 @@ # fill_in('field1', with: 'should sync') # expect(find('#field2').value).to eq('should sync') # end -# end \ No newline at end of file +# end diff --git a/spec/integration/todos_spec.rb b/spec/integration/todos_spec.rb index 59c4b09b..b0f8b7c5 100644 --- a/spec/integration/todos_spec.rb +++ b/spec/integration/todos_spec.rb @@ -4,7 +4,7 @@ it 'should add a todo and remove it' do visit '/todos' - fill_in 'newtodo', :with => 'Todo 1' + fill_in 'newtodo', with: 'Todo 1' find('#newtodo').native.send_keys(:return) expect(page).to have_content('Todo 1') @@ -19,4 +19,4 @@ page.driver.browser.navigate.refresh expect(page).to_not have_content('Todo 1') end -end \ No newline at end of file +end diff --git a/spec/integration/user_spec.rb b/spec/integration/user_spec.rb index bdf458d1..6fe37a4c 100644 --- a/spec/integration/user_spec.rb +++ b/spec/integration/user_spec.rb @@ -19,7 +19,6 @@ expect(page).to have_content('Test Account 9550') end - it 'should fail to create an account without a valid email and password' do visit '/' @@ -40,10 +39,10 @@ expect(page).to have_content('must be at least 8 characters') end - describe "with a user" do + describe 'with a user' do before do - # Add the user - store._users! << { email: 'test@test.com', password: 'awes0mesEcRet', name: 'Test Account 9550' } + # Add the user + store._users! << { email: 'test@test.com', password: 'awes0mesEcRet', name: 'Test Account 9550' } end it 'should login and logout' do @@ -89,5 +88,4 @@ expect(page).to have_content('Password did not match') end end - end diff --git a/spec/models/associations_spec.rb b/spec/models/associations_spec.rb index 61842767..6da6d2f5 100644 --- a/spec/models/associations_spec.rb +++ b/spec/models/associations_spec.rb @@ -15,7 +15,7 @@ class ::ZipInfo < Volt::Model describe Volt::Associations do if RUBY_PLATFORM != 'opal' - describe "with samples" do + describe 'with samples' do before do @person = Person.new(name: 'Jimmy') store.people << @person @@ -31,7 +31,6 @@ class ::ZipInfo < Volt::Model it 'should associate via has_many' do store._people!.first do |person| - addresses = person.addresses.all expect(addresses.size.sync).to eq(2) expect(addresses[0]._city.sync).to eq('Bozeman') @@ -42,15 +41,15 @@ class ::ZipInfo < Volt::Model store = Volt::Model.new({}, persistor: Volt::Persistors::Flash) expect do store.send(:association_with_root_model, :blah) - end.to raise_error("blah currently only works on the store and page collection "\ - "(support for other collections coming soon)") + end.to raise_error('blah currently only works on the store and page collection '\ + '(support for other collections coming soon)') end end it 'should support has_one' do - address = store.addresses.create({street: '223344 Something St'}).sync + address = store.addresses.create(street: '223344 Something St').sync - zip_info = store.zip_infos.create({zip: '29344', address_id: address.id}).sync + zip_info = store.zip_infos.create(zip: '29344', address_id: address.id).sync address2 = store.addresses.first.sync expect(address2.zip_info.sync.id).to eq(zip_info.id) @@ -59,12 +58,12 @@ class ::ZipInfo < Volt::Model it 'should raise an exception when setting up a plural has one' do expect do Address.send(:has_one, :isotopes) - end.to raise_error(NameError, "has_one takes a singluar association name") + end.to raise_error(NameError, 'has_one takes a singluar association name') end it 'should assign the reference_id for has_many' do bob = store.people.create.sync - address = bob.addresses.create({:street => '1234 awesome street'}) + address = bob.addresses.create({ street: '1234 awesome street' }) expect(bob.addresses[0].sync.person_id).to eq(bob.id) expect(bob.id).to_not eq(nil) end diff --git a/spec/models/buffer_spec.rb b/spec/models/buffer_spec.rb index 73dbdc5c..b2ff6826 100644 --- a/spec/models/buffer_spec.rb +++ b/spec/models/buffer_spec.rb @@ -31,8 +31,8 @@ def change_attributes buffer = the_page._test_changed_attributes.buffer buffer.save!.sync - expect(buffer.save_to.attributes.without(:id)).to eq({one: 1, two: 2}) - expect(buffer.attributes.without(:id)).to eq({one: 1, two: 2}) + expect(buffer.save_to.attributes.without(:id)).to eq(one: 1, two: 2) + expect(buffer.attributes.without(:id)).to eq(one: 1, two: 2) expect(buffer.id).to eq(buffer.save_to.id) end diff --git a/spec/models/field_helpers_spec.rb b/spec/models/field_helpers_spec.rb index 19e36261..13911495 100644 --- a/spec/models/field_helpers_spec.rb +++ b/spec/models/field_helpers_spec.rb @@ -9,7 +9,6 @@ class ExampleModelWithField < Volt::Model describe 'field helpers' do let(:model) { ExampleModelWithField.new } it 'should allow a user to setup a field that can be written to and read' do - expect(model.name).to eq(nil) model.name = 'jimmy' expect(model.name).to eq('jimmy') diff --git a/spec/models/model_helpers/model_helpers_spec.rb b/spec/models/model_helpers/model_helpers_spec.rb index 62353692..139789cf 100644 --- a/spec/models/model_helpers/model_helpers_spec.rb +++ b/spec/models/model_helpers/model_helpers_spec.rb @@ -5,4 +5,4 @@ # model = store._posts.create # expect(model.root).to eq(store) # end -end \ No newline at end of file +end diff --git a/spec/models/model_spec.rb b/spec/models/model_spec.rb index 5044530e..6866b983 100644 --- a/spec/models/model_spec.rb +++ b/spec/models/model_spec.rb @@ -430,15 +430,15 @@ def name=(val) # Remove id's nested items = all_items.map do |hash| - hash.without(:id).map do |k,v| + hash.without(:id).map do |k, v| v = v.without(:id) if v.is_a?(Hash) - [k,v] + [k, v] end.to_h end expect(items).to eq(a) end - describe "first or create" do + describe 'first or create' do it 'should create an item if one does not exist in the collection' do page = Volt::Model.new @@ -588,9 +588,9 @@ def name=(val) describe 'destroy' do it 'fails if attempting to destroy while parentless' do - model = Volt::Model.new(test: "yeah") + model = Volt::Model.new(test: 'yeah') expect { model.destroy }.to raise_error(RuntimeError, - 'Model does not have a parent and cannot be deleted.') + 'Model does not have a parent and cannot be deleted.') end end diff --git a/spec/models/permissions_spec.rb b/spec/models/permissions_spec.rb index 34e6a1ca..140ac958 100644 --- a/spec/models/permissions_spec.rb +++ b/spec/models/permissions_spec.rb @@ -50,7 +50,7 @@ class ::TestUpdateReadCheck < Volt::Model let(:user_todo) { TestUserTodo.new } it 'auto-associates users via own_by_user' do - #TODO: better assertions + # TODO: better assertions expect(user_todo.respond_to?(:user)).to be(true) end diff --git a/spec/models/persistors/store_spec.rb b/spec/models/persistors/store_spec.rb index 4f3cdf8d..22fa9061 100644 --- a/spec/models/persistors/store_spec.rb +++ b/spec/models/persistors/store_spec.rb @@ -39,7 +39,7 @@ unless RUBY_PLATFORM == 'opal' before do model = store._nesters.create(name: 'One').sync - model._subone = {name: 'Two'} + model._subone = { name: 'Two' } end it 'should reload a model with nested hash models' do diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index c6a50ab9..fd73e30d 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -64,7 +64,6 @@ def use_username bob.save!.sync Volt.as_user(bob) do - expect(bob.password).to eq(nil) bob_buf = bob.buffer @@ -81,8 +80,6 @@ def use_username end end - - describe 'when it is not a Volt server' do before do allow(Volt).to receive(:server?).and_return false diff --git a/spec/models/validations_spec.rb b/spec/models/validations_spec.rb index 573bbd76..c4e940a6 100644 --- a/spec/models/validations_spec.rb +++ b/spec/models/validations_spec.rb @@ -15,7 +15,6 @@ end end - let(:test_model_with_promises) do Class.new(Volt::Model) do attr_accessor :ran_promise @@ -164,5 +163,4 @@ model._name = 'ok' # fails again expect(model._name).to eq('Jimmy') end - end diff --git a/spec/models/validators/block_validations_spec.rb b/spec/models/validators/block_validations_spec.rb index bf4bf370..4ce18194 100644 --- a/spec/models/validators/block_validations_spec.rb +++ b/spec/models/validators/block_validations_spec.rb @@ -7,9 +7,7 @@ let(:test_model_class) do Class.new(Volt::Model) do validations do - if _is_ready == true - validate :name, length: 5 - end + validate :name, length: 5 if _is_ready == true end end end @@ -18,9 +16,7 @@ Class.new(Volt::Model) do validations do |action| # Only validation the name on update - if action == :update - validate :name, length: 5 - end + validate :name, length: 5 if action == :update end end end @@ -47,7 +43,6 @@ jo.validate!.sync expect(jo.errors.size).to eq(1) - end end -end \ No newline at end of file +end diff --git a/spec/models/validators/format_validator_spec.rb b/spec/models/validators/format_validator_spec.rb index a2811381..0041868c 100644 --- a/spec/models/validators/format_validator_spec.rb +++ b/spec/models/validators/format_validator_spec.rb @@ -5,7 +5,7 @@ # Feel free to append stub methods to this class as needed for testing. class SpecValidator < Volt::FormatValidator def default_options - "No hash here, no sir!" + 'No hash here, no sir!' end end @@ -49,7 +49,7 @@ def default_options context 'when default_options is not a Hash' do it 'returns the options hash instead of default_options' do - user = Volt::Model.new(email: "rick@nolematad.io") + user = Volt::Model.new(email: 'rick@nolematad.io') validator = SpecValidator.new(user, 'email') options = { with: /.+@.+/, message: 'must include an @ symbol' } results = validator.apply(options).errors diff --git a/spec/models/validators/type_validator_spec.rb b/spec/models/validators/type_validator_spec.rb index 4d41b16b..be920822 100644 --- a/spec/models/validators/type_validator_spec.rb +++ b/spec/models/validators/type_validator_spec.rb @@ -20,7 +20,7 @@ describe 'when count is a string' do let(:count) { 'Cats' } it do - expect(subject).to eq({count: ['must be of type Numeric']}) + expect(subject).to eq(count: ['must be of type Numeric']) end end end diff --git a/spec/page/bindings/content_binding_spec.rb b/spec/page/bindings/content_binding_spec.rb index f4293050..c725873f 100644 --- a/spec/page/bindings/content_binding_spec.rb +++ b/spec/page/bindings/content_binding_spec.rb @@ -30,7 +30,6 @@ volt_app = double('volt/app') expect(volt_app).to receive(:page).and_return(page) - dom = Volt::AttributeTarget.new(0) Volt::TemplateRenderer.new(volt_app, dom, context, 'main', 'main/main') diff --git a/spec/page/bindings/each_binding_spec.rb b/spec/page/bindings/each_binding_spec.rb index f3b12aba..e42d9e45 100644 --- a/spec/page/bindings/each_binding_spec.rb +++ b/spec/page/bindings/each_binding_spec.rb @@ -8,23 +8,22 @@ class ::TestEachBindingController < Volt::ModelController it 'should render an each binding' do dom = Volt::AttributeTarget.new(0) context = ::TestEachBindingController.new(volt_app) - context._items << {name: 'One'} - context._items << {name: 'Two'} + context._items << { name: 'One' } + context._items << { name: 'Two' } - - getter = Proc.new { context._items } + getter = proc { context._items } variable_name = 'item' index_name = 'index' template_name = 'main/item' # Setup the each binding - each_binding = ->(volt_app, target, context, id) do + each_binding = lambda do |volt_app, target, context, id| Volt::EachBinding.new(volt_app, target, context, id, getter, variable_name, index_name, template_name) end # Setup a content binding to make sure its passing the right item - content_binding = ->(volt_app, target, context, id) do + content_binding = lambda do |volt_app, target, context, id| Volt::ContentBinding.new(volt_app, target, context, id, proc { item._name }) end @@ -52,8 +51,8 @@ class ::TestEachBindingController < Volt::ModelController expect(dom.to_html).to eq('hello One, Two, ') - context._items << {name: 'Three'} + context._items << { name: 'Three' } Volt::Computation.flush! expect(dom.to_html).to eq('hello One, Two, Three, ') end -end \ No newline at end of file +end diff --git a/spec/page/bindings/if_binding_spec.rb b/spec/page/bindings/if_binding_spec.rb index 31cbf840..3469799f 100644 --- a/spec/page/bindings/if_binding_spec.rb +++ b/spec/page/bindings/if_binding_spec.rb @@ -21,7 +21,7 @@ class ::TestIfBindingController < Volt::ModelController ] ] - binding = ->(volt_app, target, context, id) do + binding = lambda do |volt_app, target, context, id| Volt::IfBinding.new(volt_app, target, context, 0, branches) end @@ -54,4 +54,4 @@ class ::TestIfBindingController < Volt::ModelController Volt::Computation.flush! expect(dom.to_html).to eq('no, false') end -end \ No newline at end of file +end diff --git a/spec/page/bindings/template_binding/view_lookup_for_path_spec.rb b/spec/page/bindings/template_binding/view_lookup_for_path_spec.rb index a475f418..1d894fc9 100644 --- a/spec/page/bindings/template_binding/view_lookup_for_path_spec.rb +++ b/spec/page/bindings/template_binding/view_lookup_for_path_spec.rb @@ -149,5 +149,4 @@ def set_template(templates) expect(@view_lookup.path_for_template('not/a/real/item/')).to eq([nil, nil]) end - end diff --git a/spec/reactive/computation_spec.rb b/spec/reactive/computation_spec.rb index fddb75fd..78757395 100644 --- a/spec/reactive/computation_spec.rb +++ b/spec/reactive/computation_spec.rb @@ -123,7 +123,6 @@ end failure = lambda do |error| - end -> { promise }.watch_and_resolve!(success, failure) @@ -146,7 +145,7 @@ success = lambda do |val| results << val end - -> { dep.depend ; cur_val }.watch_and_resolve!(success) + -> { dep.depend; cur_val }.watch_and_resolve!(success) expect(results).to eq([]) @@ -170,7 +169,7 @@ results << val end - -> { dep.depend ; cur_val }.watch_and_resolve!(success, nil, true) + -> { dep.depend; cur_val }.watch_and_resolve!(success, nil, true) expect(results).to eq([nil]) @@ -189,7 +188,7 @@ results << val end - computation = -> { dep.depend ; cur_val }.watch_and_resolve!(success) + computation = -> { dep.depend; cur_val }.watch_and_resolve!(success) expect(results).to eq([]) @@ -204,7 +203,7 @@ cur_val = Promise.new results = [] - success = lambda {} + success = -> {} failure = lambda do |error| results << error end diff --git a/spec/reactive/eventable_spec.rb b/spec/reactive/eventable_spec.rb index 0f7f0c3a..488c95a0 100644 --- a/spec/reactive/eventable_spec.rb +++ b/spec/reactive/eventable_spec.rb @@ -73,14 +73,14 @@ def trigger_works_event! end it 'Shows object ID and events when inspected' do - tested = TestEventable.new.on("test") { nil } + tested = TestEventable.new.on('test') { nil } inspected = tested.inspect expect(inspected).to include(tested.object_id.to_s) expect(inspected).to include(tested.events.first.to_s) end it 'calls event_removed on the class included on removal of event' do - listener = test_eventable.on("test") { nil } + listener = test_eventable.on('test') { nil } listener.remove expect(test_eventable.events_removed).to include(test: [true, true]) end diff --git a/spec/reactive/reactive_hash_spec.rb b/spec/reactive/reactive_hash_spec.rb index 3995b79d..1fd8b2f6 100644 --- a/spec/reactive/reactive_hash_spec.rb +++ b/spec/reactive/reactive_hash_spec.rb @@ -11,7 +11,7 @@ end it 'should return to_json' do - a = Volt::ReactiveHash.new({name: 'bob'}) + a = Volt::ReactiveHash.new(name: 'bob') expect(a.to_json).to eq("{\"name\":\"bob\"}") end end diff --git a/spec/server/component_templates_spec.rb b/spec/server/component_templates_spec.rb index f2316a49..032cabb2 100644 --- a/spec/server/component_templates_spec.rb +++ b/spec/server/component_templates_spec.rb @@ -5,16 +5,16 @@ require 'volt/server/component_templates' describe Volt::ComponentTemplates do - let(:haml_handler) do + let(:haml_handler) do double(:haml_handler) end it 'can be extended' do - expect( Volt::ComponentTemplates::Handlers.extensions ).to eq([ :html, :email ]) + expect(Volt::ComponentTemplates::Handlers.extensions).to eq([:html, :email]) - Volt::ComponentTemplates.register_template_handler(:haml, haml_handler) + Volt::ComponentTemplates.register_template_handler(:haml, haml_handler) - expect( Volt::ComponentTemplates::Handlers.extensions ).to eq([ :html, :email, :haml ]) + expect(Volt::ComponentTemplates::Handlers.extensions).to eq([:html, :email, :haml]) end end diff --git a/spec/server/html_parser/view_parser_spec.rb b/spec/server/html_parser/view_parser_spec.rb index 45571956..ff7ea644 100644 --- a/spec/server/html_parser/view_parser_spec.rb +++ b/spec/server/html_parser/view_parser_spec.rb @@ -194,7 +194,7 @@ view = Volt::ViewParser.new(html, 'main/main/main/body') expected = " Link\n" - expect(view.templates["main/main/main/body/body"]["html"]).to eq expected + expect(view.templates['main/main/main/body/body']['html']).to eq expected end it 'should parse components' do diff --git a/spec/server/message_bus/message_encoder_spec.rb b/spec/server/message_bus/message_encoder_spec.rb index c557af74..9d2f7bcd 100644 --- a/spec/server/message_bus/message_encoder_spec.rb +++ b/spec/server/message_bus/message_encoder_spec.rb @@ -7,7 +7,7 @@ allow_any_instance_of(Volt::MessageBus).to receive(:connect_to_peers).and_return(nil) end - describe "encryption" do + describe 'encryption' do before do @msg_bus_config = double('volt/config') @@ -44,6 +44,5 @@ expect(decrypted_message).to eq(message) end - end -end \ No newline at end of file +end diff --git a/spec/server/message_bus/peer_to_peer/peer_connection_spec.rb b/spec/server/message_bus/peer_to_peer/peer_connection_spec.rb index 0b93f830..3a8ac307 100644 --- a/spec/server/message_bus/peer_to_peer/peer_connection_spec.rb +++ b/spec/server/message_bus/peer_to_peer/peer_connection_spec.rb @@ -105,8 +105,7 @@ def still_alive?(*args) conn1.disconnect conn2.disconnect - end end end -end \ No newline at end of file +end diff --git a/spec/server/message_bus/peer_to_peer/peer_server_spec.rb b/spec/server/message_bus/peer_to_peer/peer_server_spec.rb index 58aa0a13..f4d81aeb 100644 --- a/spec/server/message_bus/peer_to_peer/peer_server_spec.rb +++ b/spec/server/message_bus/peer_to_peer/peer_server_spec.rb @@ -2,7 +2,7 @@ unless RUBY_PLATFORM == 'opal' describe Volt::MessageBus::PeerServer do - describe "ip and ports" do + describe 'ip and ports' do before do allow_any_instance_of(Volt::MessageBus::PeerServer).to receive(:run_server) end @@ -12,7 +12,7 @@ expect(Volt.config).to receive(:message_bus).and_return(config) .at_least(:once) - ports = [5000,6000,7000] + ports = [5000, 6000, 7000] expect(config).to receive(:bind_port_ranges).and_return(ports) .at_least(:once) @@ -61,6 +61,5 @@ peer_server = Volt::MessageBus::PeerServer.new(message_bus) end.to raise_error(Exception) end - end -end \ No newline at end of file +end diff --git a/spec/server/message_bus/peer_to_peer/socket_with_timeout_spec.rb b/spec/server/message_bus/peer_to_peer/socket_with_timeout_spec.rb index b1560f34..72d0c9c6 100644 --- a/spec/server/message_bus/peer_to_peer/socket_with_timeout_spec.rb +++ b/spec/server/message_bus/peer_to_peer/socket_with_timeout_spec.rb @@ -8,4 +8,4 @@ Volt::SocketWithTimeout.new('google.com', 80, 10) end end -end \ No newline at end of file +end diff --git a/spec/server/message_bus/peer_to_peer_spec.rb b/spec/server/message_bus/peer_to_peer_spec.rb index a5efbd17..ece0a719 100644 --- a/spec/server/message_bus/peer_to_peer_spec.rb +++ b/spec/server/message_bus/peer_to_peer_spec.rb @@ -6,6 +6,5 @@ # Stub socket stuff allow_any_instance_of(Volt::MessageBus::PeerToPeer).to receive(:connect_to_peers).and_return(nil) end - end -end \ No newline at end of file +end diff --git a/spec/server/middleware/middleware_handler.rb b/spec/server/middleware/middleware_handler.rb index 53acabd6..37c3e057 100644 --- a/spec/server/middleware/middleware_handler.rb +++ b/spec/server/middleware/middleware_handler.rb @@ -21,4 +21,4 @@ ]) end end -end \ No newline at end of file +end diff --git a/spec/server/rack/http_resource_spec.rb b/spec/server/rack/http_resource_spec.rb index 870deee1..d2a124fd 100644 --- a/spec/server/rack/http_resource_spec.rb +++ b/spec/server/rack/http_resource_spec.rb @@ -62,8 +62,7 @@ def show request = Volt::HttpRequest.new(env) response = http_resource.call(env) expect(response[0]).to eq(404) - #expect(response.body).to eq(['show with id 99 and another_param called']) + # expect(response.body).to eq(['show with id 99 and another_param called']) end - end end diff --git a/spec/tasks/user_tasks_spec.rb b/spec/tasks/user_tasks_spec.rb index 25e58cd9..96e3a063 100644 --- a/spec/tasks/user_tasks_spec.rb +++ b/spec/tasks/user_tasks_spec.rb @@ -9,7 +9,7 @@ double('FakeUsersCollection', where: fake_response) end - let(:fake_store) { double('FakeStore', :_users => fake_users_collection) } + let(:fake_store) { double('FakeStore', _users: fake_users_collection) } let(:login_info) { { 'login' => 'Marty', 'password' => 'McFly' } } @@ -26,8 +26,8 @@ let(:user) { false } it 'raises VoltUserError' do - expect { subject.login(login_info) }. - to raise_error('User could not be found') + expect { subject.login(login_info) } + .to raise_error('User could not be found') end end @@ -36,15 +36,15 @@ let(:user) { double('User', id: 1, _hashed_password: password) } it 'fails on bad password' do - expect { subject.login(login_info.merge 'password' => 'Not McFly') }. - to raise_error('Password did not match') + expect { subject.login(login_info.merge 'password' => 'Not McFly') } + .to raise_error('Password did not match') end it 'fails with missing app_secret' do allow(Volt.config).to receive(:app_secret).and_return false - expect { subject.login(login_info) }. - to raise_error('app_secret is not configured') + expect { subject.login(login_info) } + .to raise_error('app_secret is not configured') end it 'generates a signature digest' do diff --git a/spec/utils/ejson_spec.rb b/spec/utils/ejson_spec.rb index 6619891f..dcddad4f 100644 --- a/spec/utils/ejson_spec.rb +++ b/spec/utils/ejson_spec.rb @@ -2,7 +2,7 @@ describe Volt::EJSON, '.parse' do subject { Volt::EJSON } - let(:epoch) { 135820576553 } + let(:epoch) { 135_820_576_553 } let(:ruby_epoch) { epoch / 1000.0 } context 'safe escaping' do @@ -22,8 +22,8 @@ context 'parsing EJSON fields' do context 'date' do it 'is not parsed when given a bad value' do - expect(subject.parse '{"a": {"$date" : "something"}}'). - to eq('a' => { '$date' => 'something' }) + expect(subject.parse '{"a": {"$date" : "something"}}') + .to eq('a' => { '$date' => 'something' }) end it 'parses proper $date EJSON fields' do @@ -52,8 +52,8 @@ end expect(subject.parse ejson).to eq( - "when" => Time.at(ruby_epoch), - "then" => Time.at(ruby_epoch) + 'when' => Time.at(ruby_epoch), + 'then' => Time.at(ruby_epoch) ) end end @@ -98,4 +98,4 @@ expect(stringified).to eq '{"$escape":{"$date":"something"}}' end end -end \ No newline at end of file +end diff --git a/spec/utils/promise_extensions_spec.rb b/spec/utils/promise_extensions_spec.rb index af994a41..33b87060 100644 --- a/spec/utils/promise_extensions_spec.rb +++ b/spec/utils/promise_extensions_spec.rb @@ -1,20 +1,19 @@ require 'spec_helper' +def count_occurences(str, find) + count = 0 - def count_occurences(str, find) - count = 0 + loop do + index = str.index(find) - loop do - index = str.index(find) - - break unless index - count += 1 - str = str[index+1..-1] - end - - count + break unless index + count += 1 + str = str[index + 1..-1] end + count +end + describe Promise do it 'should allow you to call methods that will be called on the resolved value and return a new promise' do a = Promise.new.resolve(5) @@ -55,4 +54,4 @@ def count_occurences(str, find) a.something end.not_to raise_error end -end \ No newline at end of file +end diff --git a/spec/utils/task_argument_filtererer_spec.rb b/spec/utils/task_argument_filtererer_spec.rb index afbdc365..01b99e95 100644 --- a/spec/utils/task_argument_filtererer_spec.rb +++ b/spec/utils/task_argument_filtererer_spec.rb @@ -15,9 +15,8 @@ end it 'should create and run a new TaskArgumentFilterer when its filter method is called' do - filtered_args = TaskArgumentFilterer.filter([{login: 'jam@jam.com', password: 'some password'}]) - expect(filtered_args).to eq([{:login=>"jam@jam.com", :password=>"[FILTERED]"}]) + filtered_args = TaskArgumentFilterer.filter([{ login: 'jam@jam.com', password: 'some password' }]) + expect(filtered_args).to eq([{ login: 'jam@jam.com', password: '[FILTERED]' }]) end - end end diff --git a/templates/component/config/initializers/boot.rb b/templates/component/config/initializers/boot.rb index a4bbae35..312263ce 100644 --- a/templates/component/config/initializers/boot.rb +++ b/templates/component/config/initializers/boot.rb @@ -7,4 +7,4 @@ # To include code only on the server, use: # unless RUBY_PLATFORM == 'opal' # ^^ this will not send compile in code in the conditional to the client. -# ^^ this include code required in the conditional. \ No newline at end of file +# ^^ this include code required in the conditional. diff --git a/templates/newgem/app/newgem/config/initializers/boot.rb b/templates/newgem/app/newgem/config/initializers/boot.rb index a4bbae35..312263ce 100644 --- a/templates/newgem/app/newgem/config/initializers/boot.rb +++ b/templates/newgem/app/newgem/config/initializers/boot.rb @@ -7,4 +7,4 @@ # To include code only on the server, use: # unless RUBY_PLATFORM == 'opal' # ^^ this will not send compile in code in the conditional to the client. -# ^^ this include code required in the conditional. \ No newline at end of file +# ^^ this include code required in the conditional. diff --git a/templates/project/app/main/config/initializers/boot.rb b/templates/project/app/main/config/initializers/boot.rb index a4bbae35..312263ce 100644 --- a/templates/project/app/main/config/initializers/boot.rb +++ b/templates/project/app/main/config/initializers/boot.rb @@ -7,4 +7,4 @@ # To include code only on the server, use: # unless RUBY_PLATFORM == 'opal' # ^^ this will not send compile in code in the conditional to the client. -# ^^ this include code required in the conditional. \ No newline at end of file +# ^^ this include code required in the conditional. diff --git a/templates/project/app/main/models/user.rb b/templates/project/app/main/models/user.rb index 1dbf70a3..f8cd15db 100644 --- a/templates/project/app/main/models/user.rb +++ b/templates/project/app/main/models/user.rb @@ -8,5 +8,4 @@ class User < Volt::User validate login_field, unique: true, length: 8 validate :email, email: true - end diff --git a/volt.gemspec b/volt.gemspec index db9cab5d..ec60be32 100644 --- a/volt.gemspec +++ b/volt.gemspec @@ -34,7 +34,6 @@ Gem::Specification.new do |spec| # be deprecated (which we need to build a work around for) spec.add_dependency 'concurrent-ruby', '= 0.8.0' - # For user passwords spec.add_dependency 'bcrypt', '~> 3.1.9'