Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rubocop #38

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Marthyn This is the opposite of the default StringLiterals EnforcedStyle value. What is the reasoning behind this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its default hoppinger rubocop style. But I shall change it to single quotes
Sent from my iPhone

On Wed, Jun 10, 2015 at 8:19 AM -0700, "Sebastiaan" [email protected] wrote:

+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

This is the opposite of the default StringLiterals EnforcedStyle value. What is the reasoning behind this?


Reply to this email directly or view it on GitHub:
https://github.com/wponrails/wp-connector/pull/38/files#r32128879


Style/ClassAndModuleChildren:
EnforcedStyle: nested
1 change: 0 additions & 1 deletion Rakefile
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
require "bundler/gem_tasks"

6 changes: 3 additions & 3 deletions app/controllers/concerns/wp_preview_tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

#
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions app/controllers/concerns/wp_webhook_endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand All @@ -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
61 changes: 29 additions & 32 deletions app/models/concerns/wp_cache.rb
Original file line number Diff line number Diff line change
@@ -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.
#
Expand All @@ -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)
Expand All @@ -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

Expand All @@ -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

#
Expand All @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion app/models/concerns/wp_menu.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def update_menu(json)

module ClassMethods
def wp_type
'menus'
"menus"
end
end
end
12 changes: 6 additions & 6 deletions app/models/concerns/wp_post.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion app/models/concerns/wp_seo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 5 additions & 7 deletions app/models/concerns/wp_term.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions app/workers/wp_api_worker.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require 'sidekiq'
require "sidekiq"

#
# This worker is used to schedule a `create_or_update` class method call
Expand All @@ -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
7 changes: 0 additions & 7 deletions lib/wp-connector.rb

This file was deleted.

7 changes: 7 additions & 0 deletions lib/wp_connector.rb
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion lib/wp-connector/railtie.rb → lib/wp_connector/railtie.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'wp-connector'
require "wp_connector"

module WpConnector
class Railtie < Rails::Railtie
end
Expand Down
File renamed without changes.