From 5ece33b029d46d170597b16a3714867ac68e16fb Mon Sep 17 00:00:00 2001 From: Marthyn Date: Thu, 11 Jun 2015 10:40:59 +0200 Subject: [PATCH] Rubocop style issues --- .rubocop.yml | 54 ++++++++++++++++ Rakefile | 1 - app/controllers/concerns/wp_preview_tools.rb | 6 +- .../concerns/wp_webhook_endpoint.rb | 8 +-- app/models/concerns/wp_cache.rb | 61 +++++++++---------- app/models/concerns/wp_menu.rb | 2 +- app/models/concerns/wp_post.rb | 12 ++-- app/models/concerns/wp_seo.rb | 2 +- app/models/concerns/wp_term.rb | 12 ++-- app/workers/wp_api_worker.rb | 4 +- lib/wp-connector.rb | 7 --- lib/wp_connector.rb | 7 +++ lib/{wp-connector => wp_connector}/railtie.rb | 3 +- lib/{wp-connector => wp_connector}/version.rb | 0 14 files changed, 114 insertions(+), 65 deletions(-) create mode 100644 .rubocop.yml delete mode 100644 lib/wp-connector.rb create mode 100644 lib/wp_connector.rb rename lib/{wp-connector => wp_connector}/railtie.rb (72%) rename lib/{wp-connector => wp_connector}/version.rb (100%) diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..dcb75bb --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,54 @@ +Documentation: + Enabled: true + +AllCops: + Include: + - "**/Rakefile" + - "**/config.ru" + Exclude: + - "db/**/*" + - "tmp/**/*" + - "vendor/**/*" + - "bin/**/*" + - "log/**/*" + RunRailsCops: true + +Documentation: + Enabled: false +Style/LineLength: + Max: 145 +Metrics/AbcSize: + Max: 30 +Metrics/BlockNesting: + Max: 3 +Metrics/ClassLength: + CountComments: false # count full line comments? + Max: 100 +Metrics/CyclomaticComplexity: + Max: 6 +Metrics/LineLength: + Max: 80 + AllowURI: true + URISchemes: + - http + - https + +Style/ClassAndModuleChildren: + Enabled: false + +Metrics/MethodLength: + CountComments: false # count full line comments? + Max: 13 + +Metrics/ParameterLists: + Max: 5 + CountKeywordArgs: true + +Metrics/PerceivedComplexity: + Max: 7 + +StringLiterals: + EnforcedStyle: double_quotes + +Style/ClassAndModuleChildren: + EnforcedStyle: nested diff --git a/Rakefile b/Rakefile index 809eb56..2995527 100644 --- a/Rakefile +++ b/Rakefile @@ -1,2 +1 @@ require "bundler/gem_tasks" - diff --git a/app/controllers/concerns/wp_preview_tools.rb b/app/controllers/concerns/wp_preview_tools.rb index 98b44e7..bc78e0f 100644 --- a/app/controllers/concerns/wp_preview_tools.rb +++ b/app/controllers/concerns/wp_preview_tools.rb @@ -13,13 +13,13 @@ def validate_preview_token(wp_post_model, &block) return if wp_post_model.status == "publish" unless params[:token] == token(wp_post_model) - head :unauthorized and return unless block_given? + head :unauthorized && return unless block_given? block.call end # return true for clearer debugging - return true + true end # @@ -35,7 +35,7 @@ def token(wp_post_model) # This to avoid NotFound errors due to the delaying of WP API calls. # def retry_when_preview(retrying = false, &block) - raise "retry_when_preview requires a block" unless block_given? + fail "retry_when_preview requires a block" unless block_given? return block.call rescue ActiveRecord::ActiveRecordError => e raise e if !params[:preview] || retrying diff --git a/app/controllers/concerns/wp_webhook_endpoint.rb b/app/controllers/concerns/wp_webhook_endpoint.rb index 0acbd41..8d32285 100644 --- a/app/controllers/concerns/wp_webhook_endpoint.rb +++ b/app/controllers/concerns/wp_webhook_endpoint.rb @@ -24,7 +24,7 @@ def wp_id_from_params # Convenience method for finding the `preview` of an incoming POST request. # def preview_from_params - # some systems send in a string '1' or '0' for booleans. Map it to boolean: + # some systems send in a string "1" or "0" for booleans. Map it to boolean: to_bool params[:preview] end @@ -33,9 +33,9 @@ def preview_from_params # def render_json_200_or_404(success) if success - render json: {status: 200, message: 'OK'} + render json: { status: 200, message: "OK" } else - render json: {status: 404, message: 'Not found'} + render json: { status: 404, message: "Not found" } end end @@ -49,6 +49,6 @@ def require_valid_api_key def to_bool(string) return true if string == true || string =~ (/^(true|t|yes|y|1)$/i) return false if string == false || string.blank? || string =~ (/^(false|f|no|n|0)$/i) - raise ArgumentError.new("invalid value for Boolean: \"#{string}\"") + fail(ArgumentError, "invalid value for Boolean: \"#{string}\"") end end diff --git a/app/models/concerns/wp_cache.rb b/app/models/concerns/wp_cache.rb index 001796f..dae361d 100644 --- a/app/models/concerns/wp_cache.rb +++ b/app/models/concerns/wp_cache.rb @@ -1,10 +1,10 @@ -require 'faraday' +require "faraday" module WpCache extend ActiveSupport::Concern module ClassMethods - + attr_reader :classes # # Collect all class names in a class variable so that it can be accessed by the Rake task. # @@ -13,17 +13,10 @@ def included(base) @classes << base.name end - # - # Returns an array WpCache classes. - # - def classes - @classes - end - # # Schedules a `create_or_update` call to itself. # - # TODO (cies): add a configurable amount of delay, defaulting to 0.5secs + # TODO: (cies) add a configurable amount of delay, defaulting to 0.5secs def schedule_create_or_update(wp_id, preview = false, request = nil) extra_info = request ? " after #{request.fullpath} -- #{request.body.read}" : "" Rails.logger.info("SCHEDULED by #{self.class}" + extra_info) @@ -35,12 +28,12 @@ def schedule_create_or_update(wp_id, preview = false, request = nil) # and passes it the content by the `update_wp_cache` instance method. # def create_or_update(wp_type, wp_id, preview = false) - return unless wp_id.is_a? Fixnum or wp_id.is_a? String + return unless wp_id.is_a?(Fixnum) || wp_id.is_a?(String) maybe_preview_segment = (preview ? "preview/" : "") wp_json = get_from_wp_api "#{ wp_type }/#{ maybe_preview_segment }#{ wp_id }" # WP API will return a code if the route is incorrect or # the specified entry is none existant. If so return early. - return if wp_json[0] and invalid_api_responses.include? wp_json[0]["code"] + return if wp_json[0] && invalid_api_responses.include?(wp_json[0]["code"]) where(wp_id: wp_id).first_or_initialize.update_wp_cache(wp_json) end @@ -58,34 +51,38 @@ def create_or_update_all # the `update_wp_cache` instance method. # Removes records with unknown IDs. # - # TODO (dunyakirkali) clean up + # TODO: (dunyakirkali) clean up def create_or_update_all_paginated page = 0 ids = [] - max_page = (ENV['MAX_PAGE'].to_i == 0 ? 999 : ENV['MAX_PAGE'].to_i) - while page < max_page do + max_page = (ENV["MAX_PAGE"].to_i == 0 ? 999 : ENV["MAX_PAGE"].to_i) + while page < max_page Rails.logger.info " page #{page}" wp_json = get_from_wp_api(wp_type, page) break if wp_json.empty? - ids << wp_json.map do |json| - wp_id = json['ID'] - where(wp_id: wp_id).first_or_initialize.update_wp_cache(json) - wp_id - end - page = page + 1 + ids << map_ids(wp_json) + page += 1 end - where('wp_id NOT IN (?)', ids.flatten).destroy_all unless ids.empty? + where("wp_id NOT IN (?)", ids.flatten).destroy_all unless ids.empty? end - # TODO (dunyakirkali) doc + def map_ids + wp_json.map do |json| + wp_id = json["ID"] + where(wp_id: wp_id).first_or_initialize.update_wp_cache(json) + wp_id + end + end + + # TODO: (dunyakirkali) doc def create_or_update_all_non_paginated wp_json = get_from_wp_api(wp_type) ids = wp_json.map do |json| - wp_id = json['ID'] + wp_id = json["ID"] where(wp_id: wp_id).first_or_initialize.update_wp_cache(json) wp_id end - where('wp_id NOT IN (?)', ids).destroy_all unless ids.empty? + where("wp_id NOT IN (?)", ids).destroy_all unless ids.empty? end # @@ -102,15 +99,15 @@ def purge(wp_id) # # Convenience method for calling the WP API. # - # TODO (cies): re-raise any connection errors with more intuitive names + # TODO: (cies) re-raise any connection errors with more intuitive names def get_from_wp_api(route, page = -1) - # TODO (dunyakirkali) pass filter through args to get_from_wp_api - posts_per_page = (ENV['PER_PAGE'].to_i == -1 ? -1 : ENV['PER_PAGE'].to_i) + # TODO: (dunyakirkali) pass filter through args to get_from_wp_api + posts_per_page = (ENV["PER_PAGE"].to_i == -1 ? -1 : ENV["PER_PAGE"].to_i) base = Rails.configuration.x.wordpress_url - unless paginated_models.include?(wp_type) - url = "#{base}?json_route=/#{route}&filter[posts_per_page]=-1" - else + if paginated_models.include?(wp_type) url = "#{base}?json_route=/#{route}&filter[posts_per_page]=#{posts_per_page}&page=#{page}" + else + url = "#{base}?json_route=/#{route}&filter[posts_per_page]=-1" end Rails.logger.info url response = Faraday.get url @@ -136,7 +133,7 @@ def paginated_models # # List of invalid api responses # - # TODO (cies): refactor to WpCache::WP_API_ERROR_CODES + # TODO: (cies) refactor to WpCache::WP_API_ERROR_CODES def invalid_api_responses %w( json_no_route json_post_invalid_type json_user_cannot_read ) end diff --git a/app/models/concerns/wp_menu.rb b/app/models/concerns/wp_menu.rb index 0a08bed..887644d 100644 --- a/app/models/concerns/wp_menu.rb +++ b/app/models/concerns/wp_menu.rb @@ -14,7 +14,7 @@ def update_menu(json) module ClassMethods def wp_type - 'menus' + "menus" end end end diff --git a/app/models/concerns/wp_post.rb b/app/models/concerns/wp_post.rb index 21b3f73..c542868 100644 --- a/app/models/concerns/wp_post.rb +++ b/app/models/concerns/wp_post.rb @@ -5,27 +5,27 @@ module WpPost serialize :acf_fields end - # TODO (cies): rename to update_wp_post_attributes + # TODO: (cies) rename to update_wp_post_attributes def update_post(json) self.class.mappable_wordpress_attributes.each do |wp_attribute| send("#{wp_attribute}=", json[wp_attribute]) end - self.wp_id = json['ID'] + self.wp_id = json["ID"] # Use gmt date to ignore timezone settings in WordPress - self.published_at = json['date_gmt'] - self.order = json['menu_order'] + self.published_at = json["date_gmt"] + self.order = json["menu_order"] save! end module ClassMethods - # TODO (cies): refactor to constant WpPost::MAPPABLE_ATTRS + # TODO: (cies) refactor to constant WpPost::MAPPABLE_ATTRS def mappable_wordpress_attributes %w( slug title status content excerpt acf_fields ) end def wp_type - self.to_s.demodulize.underscore.pluralize + to_s.demodulize.underscore.pluralize end end end diff --git a/app/models/concerns/wp_seo.rb b/app/models/concerns/wp_seo.rb index ed64852..be66110 100644 --- a/app/models/concerns/wp_seo.rb +++ b/app/models/concerns/wp_seo.rb @@ -7,7 +7,7 @@ module WpSEO def update_wp_seo_attributes(json) return unless json.is_a?(Hash) - self.seo_fields = json['seo_fields'] + self.seo_fields = json["seo_fields"] save! end end diff --git a/app/models/concerns/wp_term.rb b/app/models/concerns/wp_term.rb index a57f7ba..c923d8c 100644 --- a/app/models/concerns/wp_term.rb +++ b/app/models/concerns/wp_term.rb @@ -8,24 +8,22 @@ def update_term(json) send("#{wp_attribute}=", json[wp_attribute]) end - self.wp_id = json['ID'] - if json['parent'] - self.class.where(wp_id: json['parent']['ID']).first_or_create.update_wp_cache(json['parent']) - self.parent_id = self.class.where(wp_id: json['parent']['ID']).first.id + self.wp_id = json["ID"] + if json["parent"] + self.class.where(wp_id: json["parent"]["ID"]).first_or_create.update_wp_cache(json["parent"]) + self.parent_id = self.class.find_by(wp_id: json["parent"]["ID"]).id end save! end module ClassMethods - def mappable_wordpress_attributes %w( name slug description count ) end def wp_type - self.to_s.underscore.pluralize + to_s.underscore.pluralize end - end end diff --git a/app/workers/wp_api_worker.rb b/app/workers/wp_api_worker.rb index 3d63927..32595d8 100644 --- a/app/workers/wp_api_worker.rb +++ b/app/workers/wp_api_worker.rb @@ -1,4 +1,4 @@ -require 'sidekiq' +require "sidekiq" # # This worker is used to schedule a `create_or_update` class method call @@ -12,6 +12,6 @@ def perform(klass, wp_id, preview = false) cklass = klass.constantize cklass.create_or_update(cklass.wp_type, wp_id, preview) rescue Exceptions::WpApiResponseError => e - Rails.logger.warn ("[FAILED JOB] " + e.message) + Rails.logger.warn("[FAILED JOB] #{e.message}") end end diff --git a/lib/wp-connector.rb b/lib/wp-connector.rb deleted file mode 100644 index 8f5ae83..0000000 --- a/lib/wp-connector.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'wp-connector/version' -require 'wp-connector/railtie' if defined?(Rails) -require 'exceptions' - -module WpConnector - class Engine < ::Rails::Engine; end -end diff --git a/lib/wp_connector.rb b/lib/wp_connector.rb new file mode 100644 index 0000000..71760dc --- /dev/null +++ b/lib/wp_connector.rb @@ -0,0 +1,7 @@ +require "wp_connector/version" +require "wp_connector/railtie" if defined?(Rails) +require "exceptions" + +module WpConnector + class Engine < ::Rails::Engine; end +end diff --git a/lib/wp-connector/railtie.rb b/lib/wp_connector/railtie.rb similarity index 72% rename from lib/wp-connector/railtie.rb rename to lib/wp_connector/railtie.rb index 120abbd..88279c8 100644 --- a/lib/wp-connector/railtie.rb +++ b/lib/wp_connector/railtie.rb @@ -1,4 +1,5 @@ -require 'wp-connector' +require "wp_connector" + module WpConnector class Railtie < Rails::Railtie end diff --git a/lib/wp-connector/version.rb b/lib/wp_connector/version.rb similarity index 100% rename from lib/wp-connector/version.rb rename to lib/wp_connector/version.rb