diff --git a/.rubocop.yml b/.rubocop.yml index bed6815..e576568 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -24,3 +24,6 @@ RSpec/ExampleLength: RSpec/MultipleExpectations: Enabled: false + +Style/ArgumentsForwarding: + Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 5a52118..6261761 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -6,25 +6,6 @@ # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: leading, trailing -Layout/DotPosition: - Exclude: - - 'lib/hawk/model/association.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. -# SupportedHashRocketStyles: key, separator, table -# SupportedColonStyles: key, separator, table -# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit -Layout/HashAlignment: - Exclude: - - 'lib/hawk/http.rb' - - 'lib/hawk/model/collection.rb' - - 'lib/hawk/model/finder.rb' - - 'lib/hawk/model/schema.rb' - # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: EnforcedStyle. # SupportedStyles: symmetrical, new_line, same_line @@ -32,12 +13,6 @@ Layout/MultilineMethodCallBraceLayout: Exclude: - 'lib/hawk/model/collection.rb' -# This cop supports safe autocorrection (--autocorrect). -Lint/AmbiguousOperator: - Exclude: - - 'lib/hawk/model/configurator.rb' - - 'lib/hawk/polyfills.rb' - # This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: AllowSafeAssignment. Lint/AssignmentInCondition: @@ -60,47 +35,18 @@ Lint/MissingSuper: Exclude: - 'lib/hawk/model/collection.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowPercentLiteralArrayArgument. -Lint/RedundantSplatExpansion: - Exclude: - - 'lib/hawk/model/association.rb' - Lint/ShadowingOuterLocalVariable: Exclude: - 'lib/hawk/http.rb' - 'lib/hawk/model/finder.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: strict, consistent -Lint/SymbolConversion: - Exclude: - - 'lib/hawk/model/association.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: IgnoreEmptyBlocks, AllowUnusedKeywordArguments. -Lint/UnusedBlockArgument: - Exclude: - - 'lib/hawk/model/base.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods. -Lint/UnusedMethodArgument: - Exclude: - - 'lib/hawk/http/caching.rb' - - 'lib/hawk/model/association.rb' - - 'lib/hawk/model/schema.rb' - - 'lib/hawk/model/schema/dsl.rb' - - 'lib/hawk/rake/utils.rb' - # Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. Metrics/AbcSize: Max: 40 # Configuration parameters: CountComments, CountAsOne. Metrics/ClassLength: - Max: 171 + Max: 173 # Configuration parameters: AllowedMethods, AllowedPatterns. Metrics/CyclomaticComplexity: @@ -155,25 +101,6 @@ Performance/MethodObjectAsBlock: Exclude: - 'lib/hawk/http.rb' -# This cop supports safe autocorrection (--autocorrect). -Performance/RedundantBlockCall: - Exclude: - - 'lib/hawk/http/caching.rb' - - 'lib/hawk/http/instrumentation.rb' - - 'lib/hawk/model/lookup.rb' - -# This cop supports safe autocorrection (--autocorrect). -Performance/RegexpMatch: - Exclude: - - 'lib/hawk/http.rb' - - 'lib/hawk/model/schema.rb' - -# This cop supports safe autocorrection (--autocorrect). -Performance/StringIdentifierArgument: - Exclude: - - 'lib/hawk/model/association.rb' - - 'lib/hawk/model/schema.rb' - # Configuration parameters: IgnoredMetadata. RSpec/DescribeClass: Exclude: @@ -193,52 +120,10 @@ Security/Eval: Exclude: - 'lib/hawk/model/pagination.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowOnlyRestArgument, UseAnonymousForwarding, RedundantRestArgumentNames, RedundantKeywordRestArgumentNames, RedundantBlockArgumentNames. -# RedundantRestArgumentNames: args, arguments -# RedundantKeywordRestArgumentNames: kwargs, options, opts -# RedundantBlockArgumentNames: blk, block, proc -Style/ArgumentsForwarding: - Exclude: - - 'lib/hawk/model/configurator.rb' - - 'lib/hawk/model/proxy.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, AllowedMethods, AllowedPatterns, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. -# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces -# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object -# FunctionalMethods: let, let!, subject, watch -# AllowedMethods: lambda, proc, it -Style/BlockDelimiters: - Exclude: - - 'lib/hawk/model/base.rb' - - 'lib/hawk/model/configurator.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: is_a?, kind_of? -Style/ClassCheck: - Exclude: - - 'lib/hawk/model/proxy.rb' - Style/ClassVars: Exclude: - 'lib/hawk/http/caching.rb' -# This cop supports safe autocorrection (--autocorrect). -Style/ColonMethodCall: - Exclude: - - 'lib/hawk/http/instrumentation.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: Keywords, RequireColon. -# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW, NOTE -Style/CommentAnnotation: - Exclude: - - 'lib/hawk/http.rb' - - 'lib/hawk/http/instrumentation.rb' - - 'lib/hawk/model/association.rb' - # This cop supports unsafe autocorrection (--autocorrect-all). Style/CommentedKeyword: Exclude: @@ -255,17 +140,6 @@ Style/DocumentDynamicEvalDefinition: Style/Documentation: Enabled: false -# This cop supports safe autocorrection (--autocorrect). -Style/EachWithObject: - Exclude: - - 'lib/hawk/http.rb' - -# This cop supports safe autocorrection (--autocorrect). -Style/EvalWithLocation: - Exclude: - - 'lib/hawk/linker.rb' - - 'lib/hawk/model/pagination.rb' - # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: AllowedVars. Style/FetchEnvVar: @@ -324,21 +198,6 @@ Style/IfWithSemicolon: Exclude: - 'lib/hawk/model/association.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: line_count_dependent, lambda, literal -Style/Lambda: - Exclude: - - 'lib/hawk/model/association.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline -Style/MethodDefParentheses: - Exclude: - - 'lib/hawk/http.rb' - - 'lib/hawk/model/association.rb' - Style/MissingRespondToMissing: Exclude: - 'lib/hawk/model/proxy.rb' @@ -385,72 +244,11 @@ Style/ParallelAssignment: - 'lib/hawk/model/schema.rb' - 'lib/hawk/rake/utils.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Exclude: - - 'lib/hawk/http.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, AllowedCompactTypes. -# SupportedStyles: compact, exploded -Style/RaiseArgs: - Exclude: - - 'lib/hawk/model/querying.rb' - -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantException: - Exclude: - - 'lib/hawk/rake/default_task.rb' - -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantParentheses: - Exclude: - - 'lib/hawk/model/finder.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowMultipleReturnValues. -Style/RedundantReturn: - Exclude: - - 'lib/hawk/http/caching.rb' - - 'lib/hawk/model/connection.rb' - - 'lib/hawk/rake/default_task.rb' - -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantSelf: - Exclude: - - 'lib/hawk/model/active.rb' - - 'lib/hawk/model/association.rb' - - 'lib/hawk/model/collection.rb' - - 'lib/hawk/model/connection.rb' - - 'lib/hawk/model/finder.rb' - - 'lib/hawk/model/schema.rb' - - 'lib/hawk/model/scoping.rb' - # This cop supports unsafe autocorrection (--autocorrect-all). Style/RedundantSelfAssignment: Exclude: - 'lib/hawk/model/proxy.rb' -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, AllowInnerSlashes. -# SupportedStyles: slashes, percent_r, mixed -Style/RegexpLiteral: - Exclude: - - 'lib/hawk/http.rb' - -# This cop supports safe autocorrection (--autocorrect). -Style/RescueModifier: - Exclude: - - 'lib/hawk/http.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: implicit, explicit -Style/RescueStandardError: - Exclude: - - 'lib/hawk/model/schema.rb' - # This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. # AllowedMethods: present?, blank?, presence, try, try! @@ -459,51 +257,6 @@ Style/SafeNavigation: - 'lib/hawk/http.rb' - 'lib/hawk/model/active.rb' -# This cop supports safe autocorrection (--autocorrect). -Style/StderrPuts: - Exclude: - - 'lib/hawk/http/caching.rb' - - 'lib/hawk/rake/default_task.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Exclude: - - 'lib/hawk/http/caching.rb' - - 'lib/hawk/model/collection.rb' - - 'lib/hawk/model/connection.rb' - - 'lib/hawk/rake/default_task.rb' - - 'lib/hawk/version.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: MinSize. -# SupportedStyles: percent, brackets -Style/SymbolArray: - EnforcedStyle: brackets - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInArrayLiteral: - Exclude: - - 'lib/hawk/model/schema.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInHashLiteral: - Exclude: - - 'lib/hawk/http.rb' - - 'lib/hawk/model/schema.rb' - -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, AllowedMethods. -# AllowedMethods: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym -Style/TrivialAccessors: - Exclude: - - 'lib/hawk/model/collection.rb' - # This cop supports unsafe autocorrection (--autocorrect-all). Style/ZeroLengthPredicate: Exclude: diff --git a/lib/hawk/http.rb b/lib/hawk/http.rb index e27e77b..173e798 100644 --- a/lib/hawk/http.rb +++ b/lib/hawk/http.rb @@ -14,9 +14,9 @@ class HTTP include Instrumentation DEFAULTS = { - timeout: 2, + timeout: 2, connect_timeout: 1, - params_encoding: :rack, + params_encoding: :rack # username: nil, # password: nil, } @@ -25,12 +25,12 @@ def initialize(base, options = {}) @defaults = DEFAULTS.deep_merge(options) @base = URI.parse(base).tap do |url| - unless %w(http https).include? url.scheme + unless %w[http https].include? url.scheme raise Error::Configuration, "URL '#{url}' is not valid: only http and https schemes are supported" end - url.path += '/' unless url.path =~ /\/$/ + url.path += '/' unless %r{/$}.match?(url.path) url.freeze end end @@ -111,8 +111,8 @@ def request(method, path, options) private - def build_url path - base.merge(path.sub(/^\//, '')).to_s + def build_url(path) + base.merge(path.sub(%r{^/}, '')).to_s end def response_handler(response) @@ -154,7 +154,11 @@ def response_handler(response) def parse_app_error_from(body) if body[0] == '{' && body[-1] == '}' - resp = MultiJson.load(body) rescue nil + resp = begin + MultiJson.load(body) + rescue StandardError + nil + end if resp.respond_to?(:key?) && resp.key?('error') resp = resp.fetch('error') end @@ -175,7 +179,7 @@ def build_request_options_from(method, options) end if options.key?(:options) - request.update options.delete(:options).except(:endpoint) # FIXME SPAGHETTI + request.update options.delete(:options).except(:endpoint) # FIXME: SPAGHETTI end options.each do |k, v| @@ -207,7 +211,7 @@ def typhoeus_defaults end def options_for_typhoeus(hawk_options) - hawk_options.inject({}) do |ret, (opt, val)| + hawk_options.each_with_object({}) do |(opt, val), ret| case opt when :request_timeout, :timeout ret[:timeout] = val.to_i @@ -228,8 +232,6 @@ def options_for_typhoeus(hawk_options) # ret[opt] = val end - - ret end end end diff --git a/lib/hawk/http/caching.rb b/lib/hawk/http/caching.rb index 201a879..2ce11a9 100644 --- a/lib/hawk/http/caching.rb +++ b/lib/hawk/http/caching.rb @@ -22,7 +22,7 @@ def inspect description = if cache_configured? "cache: ON #{@_cache_server} v#{@_cache_version}" else - "cache: OFF" + 'cache: OFF' end super.sub(/>$/, ", #{description}>") @@ -39,7 +39,7 @@ def cache_options protected def caching(descriptor, &block) - return block.call unless cache_configured? + return yield unless cache_configured? result = try_cache(descriptor, &block) @@ -47,7 +47,7 @@ def caching(descriptor, &block) invalidate(descriptor) end - return result + result end private @@ -56,8 +56,8 @@ def cache_key(descriptor) MultiJson.dump(descriptor) end - def try_cache(descriptor, &block) - return block.call unless descriptor[:method] == 'GET' + def try_cache(descriptor) + return yield unless descriptor[:method] == 'GET' key = cache_key(descriptor) @@ -69,14 +69,14 @@ def try_cache(descriptor, &block) ttl = descriptor[:expires_in] || @_cache_options[:expires_in] - block.call.tap do |cacheable| + yield.tap do |cacheable| # $stderr.puts "CACHE: store #{key} with ttl #{ttl}" @_cache.set(key, cacheable, ttl) end end end - def invalidate(descriptor, &block) + def invalidate(descriptor) descriptor = descriptor.dup descriptor[:method] = 'GET' descriptor[:params] ||= {} @@ -97,7 +97,7 @@ def initialize_cache(options) return if options[:disabled] unless options.key?(:server) - raise Error::Configuration, "Cache server option is mandatory" + raise Error::Configuration, 'Cache server option is mandatory' end client, server, version = connect_cache(options) @@ -121,7 +121,7 @@ def connect_cache(options) if version = client.version.fetch(server, nil) [client, server, version] else - $stderr.puts "Hawk: can't connect to memcached server #{server}" + warn "Hawk: can't connect to memcached server #{server}" nil end end diff --git a/lib/hawk/http/instrumentation.rb b/lib/hawk/http/instrumentation.rb index ab9b66a..05efb6f 100644 --- a/lib/hawk/http/instrumentation.rb +++ b/lib/hawk/http/instrumentation.rb @@ -4,7 +4,7 @@ module Instrumentation def self.included(base) # https://github.com/ifad/instrumenter if defined?(::Instrumenter) - Instrumenter.instrument base, :hawk # FIXME user-replaceable + Instrumenter.instrument base, :hawk # FIXME: user-replaceable else base.instance_eval { include Basic } end @@ -19,12 +19,12 @@ def self.suppress_verbose_output(value = nil) end module Basic - def instrument(type, payload, &block) + def instrument(type, payload) if Hawk::HTTP::Instrumentation.suppress_verbose_output - block.call payload + yield payload else start = Time.now.to_f - ret = block.call payload + ret = yield payload elapsed = (Time.now.to_f - start) * 1000 url = payload[:url].to_s @@ -33,7 +33,7 @@ def instrument(type, payload, &block) end $stderr.printf ">> \033[1mHawk #{type}: #{payload[:method]} %s (%.2fms), cache %s\033[0m\n" % [ - CGI::unescape(url), + CGI.unescape(url), elapsed, payload[:cached] ? 'HIT' : 'MISS' ] diff --git a/lib/hawk/linker.rb b/lib/hawk/linker.rb index 927bd58..7a0db80 100644 --- a/lib/hawk/linker.rb +++ b/lib/hawk/linker.rb @@ -1,7 +1,7 @@ module Hawk # Allows adding to any Ruby object an accessor referencing an {Hawk::Model}. # - # Example, assuming Bar is defined and Foo responds_to `bar_id`: + # Example, assuming Bar is defined and Foo responds_to +bar_id+: # # class Foo # include Hawk::Linker @@ -31,65 +31,65 @@ def _monomorphic_resource_accessor(entity, options) klass = options[:class_name] || entity.to_s.camelize key = options[:primary_key] || [entity, :id].join('_') - class_eval <<-RUBY, __FILE__, __LINE__ - 1 # Getter - def #{entity} - return nil unless self.#{key}.present? + class_eval <<~RUBY, __FILE__, __LINE__ + 1 # Getter + def #{entity} + return nil unless self.#{key}.present? - @_#{entity} ||= #{respond_to?(:module_parent) ? module_parent : parent}::#{klass}.find(self.#{key}) - end + @_#{entity} ||= #{respond_to?(:module_parent) ? module_parent : parent}::#{klass}.find(self.#{key}) + end RUBY - class_eval <<-RUBY, __FILE__, __LINE__ - 1 # Setter - def #{entity}=(object) - return if object.blank? + class_eval <<~RUBY, __FILE__, __LINE__ + 1 # Setter + def #{entity}=(object) + return if object.blank? - unless object.respond_to?(:id) && object.class.respond_to?(:find) - raise ArgumentError, "Invalid object: \#{object.inspect}" - end + unless object.respond_to?(:id) && object.class.respond_to?(:find) + raise ArgumentError, "Invalid object: \#{object.inspect}" + end - self.#{key} = object.id + self.#{key} = object.id - @_#{entity} = object - end + @_#{entity} = object + end RUBY - class_eval <<-RUBY, __FILE__, __LINE__ - 1 # Reloader - def reload(*) - super.tap { @_#{entity} = nil } - end + class_eval <<~RUBY, __FILE__, __LINE__ + 1 # Reloader + def reload(*) + super.tap { @_#{entity} = nil } + end RUBY end def _polymorphic_resource_accessor(entity, options) key = options[:as] || entity - class_eval <<-RUBY, __FILE__, __LINE__ - 1 # Getter - def #{entity} - return nil unless self.#{key}_id.present? && self.#{key}_type.present? + class_eval <<~RUBY, __FILE__, __LINE__ + 1 # Getter + def #{entity} + return nil unless self.#{key}_id.present? && self.#{key}_type.present? - @_#{entity} ||= self.#{key}_type.constantize.find(self.#{key}_id) - end + @_#{entity} ||= self.#{key}_type.constantize.find(self.#{key}_id) + end RUBY - class_eval <<-RUBY, __FILE__, __LINE__ - 1 # Setter - def #{entity}=(object) - return if object.blank? + class_eval <<~RUBY, __FILE__, __LINE__ + 1 # Setter + def #{entity}=(object) + return if object.blank? - unless object.respond_to?(:id) && object.class.respond_to?(:find) - raise ArgumentError, "Invalid object: \#{object.inspect}" - end + unless object.respond_to?(:id) && object.class.respond_to?(:find) + raise ArgumentError, "Invalid object: \#{object.inspect}" + end - self.#{key}_type = object.class.name - self.#{key}_id = object.id + self.#{key}_type = object.class.name + self.#{key}_id = object.id - @_#{entity} = object - end + @_#{entity} = object + end RUBY - class_eval <<-RUBY, __FILE__, __LINE__ - 1 # Reloader - def reload(*) - super.tap { @_#{entity} = nil } - end + class_eval <<~RUBY, __FILE__, __LINE__ + 1 # Reloader + def reload(*) + super.tap { @_#{entity} = nil } + end RUBY end end diff --git a/lib/hawk/model/active.rb b/lib/hawk/model/active.rb index bb00e98..1f913a8 100644 --- a/lib/hawk/model/active.rb +++ b/lib/hawk/model/active.rb @@ -19,17 +19,17 @@ def define_schema_key(key, *) end def ==(other) - unless self.respond_to?(:id) + unless respond_to?(:id) raise Error, "Can't compare #{self} as it doesn't have an .id attribute" end - other.instance_of?(self.class) && self.id == other.id + other.instance_of?(self.class) && id == other.id end alias eql? == def hash - if respond_to?(:id) && !self.id.nil? - self.id.hash + if respond_to?(:id) && !id.nil? + id.hash else super end @@ -65,7 +65,7 @@ def save end def persist! - connection.put(path_for(nil), self.attributes.merge(cache: { invalidate: path_for(nil) })) + connection.put(path_for(nil), attributes.merge(cache: { invalidate: path_for(nil) })) end end end diff --git a/lib/hawk/model/association.rb b/lib/hawk/model/association.rb index 6cc44f8..5472cb2 100644 --- a/lib/hawk/model/association.rb +++ b/lib/hawk/model/association.rb @@ -20,8 +20,8 @@ def initialize(attributes = {}, params = {}) private - def preload_associations(attributes, params, scope) - self.instance_exec(scope, attributes, &scope.preload_association) + def preload_associations(attributes, _params, scope) + instance_exec(scope, attributes, &scope.preload_association) end def add_association_object(scope, name, repr) @@ -44,22 +44,22 @@ def add_association_object(scope, name, repr) end end - def is_collection? type - [:polymorphic_belongs_to, :has_many].include? type + def is_collection?(type) + %i[polymorphic_belongs_to has_many].include? type end - def add_to_association_collection name, target + def add_to_association_collection(name, target) variable = "@_#{name}" instance_variable_set(variable, Collection.new) unless instance_variable_defined?(variable) collection = instance_variable_get(variable) target.respond_to?(:each) ? collection.concat(target) : collection.push(target) end - def set_association_value name, target - instance_variable_set("@_#{name}", target) + def set_association_value(name, target) + instance_variable_set(:"@_#{name}", target) end - def clean_inherited_params inherited, opts = {} + def clean_inherited_params(inherited, opts = {}) rv = {}.deep_merge opts rv[:options] = inherited[:options] if inherited && inherited[:options] rv @@ -94,7 +94,6 @@ def inherited(subclass) # Example (for Joe :-) # # class Foo < Hawk::Model::Base - # # has_many :bars # # preload_association do |attributes, name, type, options| @@ -105,11 +104,10 @@ def inherited(subclass) # end # end # end - # # end # - # The block would get called once, with :bars as `name`, :has_many as - # `type` and `{class_name:'Bar', primary_key:'foo_id'}` as `options`. + # The block would get called once, with :bars as +name+, :has_many as + # +type+ and +{ class_name: "Bar", primary_key : "foo_id" }+ as +options+. # # By default it looks up in the representation a property named after # the association's name and returns it, deleting it from the repr. @@ -153,10 +151,10 @@ def association?(attribute) def has_many(entities, options = {}) entity = entities.to_s.singularize klass = options[:class_name] || entity.camelize - key = options[:primary_key] || [self.name.demodulize.underscore, :id].join('_') + key = options[:primary_key] || [name.demodulize.underscore, :id].join('_') from = options[:from] as = options[:as] - # TODO params + # TODO: params _define_association(entities, :has_many, class_name: klass, primary_key: key, from: from, as: as) end @@ -171,11 +169,11 @@ def has_many(entities, options = {}) def has_one(entity, options = {}) entity = entity.to_s klass = options[:class_name] || entity.camelize - key = options[:primary_key] || [self.name.demodulize.underscore, :id].join('_') + key = options[:primary_key] || [name.demodulize.underscore, :id].join('_') from = options[:from] nested = options[:nested] as = options[:as] - # TODO params + # TODO: params _define_association(entity, :has_one, class_name: klass, primary_key: key, from: from, nested: nested, as: as) end @@ -213,7 +211,7 @@ def monomorphic_belongs_to(entity, options) def polymorphic_belongs_to(entity, options) key = [options[:as] || entity, :id].join('_') - # TODO params + # TODO: params _define_association(entity, :polymorphic_belongs_to, as: key) end @@ -228,16 +226,16 @@ def _define_association(name, type, options) # The raw associations code # CODE = { - has_many: ->(entities, options) { - klass, key, from, as = options.values_at(*[:class_name, :primary_key, :from, :as]) + has_many: lambda { |entities, options| + klass, key, from, as = options.values_at(:class_name, :primary_key, :from, :as) conditions = if as.present? - "'#{as}_id' => self.id, '#{as}_type' => '#{self.name}'" + "'#{as}_id' => self.id, '#{as}_type' => '#{name}'" else "'#{key}' => self.id" end - class_eval <<-RUBY, __FILE__, __LINE__ + 1 + class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{entities} return @_#{entities} if instance_variable_defined?('@_#{entities}') params = clean_inherited_params(self.params, #{conditions}) @@ -249,16 +247,16 @@ def #{entities} RUBY }, - has_one: ->(entity, options) { - klass, key, from, nested, as = options.values_at(*[:class_name, :primary_key, :from, :nested, :as]) + has_one: lambda { |entity, options| + klass, key, from, nested, as = options.values_at(:class_name, :primary_key, :from, :nested, :as) conditions = if as.present? - "'#{as}_id' => self.id, '#{as}_type' => '#{self.name}'" + "'#{as}_id' => self.id, '#{as}_type' => '#{name}'" else "'#{key}' => self.id" end - class_eval <<-RUBY, __FILE__, __LINE__ + 1 + class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{entity}! return @_#{entity} if instance_variable_defined?('@_#{entity}') @@ -285,28 +283,28 @@ def #{entity} RUBY }, - monomorphic_belongs_to: ->(entity, options) { - klass, key, params = options.values_at(*[:class_name, :primary_key, :params]) + monomorphic_belongs_to: lambda { |entity, options| + klass, key, params = options.values_at(:class_name, :primary_key, :params) params ||= {} - ivar = "@_#{entity}".intern + ivar = :"@_#{entity}" class_eval do define_method(entity) do return instance_variable_get(ivar) if instance_variable_defined?(ivar) - return unless (id = self.attributes.fetch(key.to_s, nil)) + return unless (id = attributes.fetch(key.to_s, nil)) - instance = self.class.model_class_for(klass). - find(id, clean_inherited_params(self.params, params)) + instance = self.class.model_class_for(klass) + .find(id, clean_inherited_params(self.params, params)) instance_variable_set(ivar, instance) end end }, - polymorphic_belongs_to: ->(entity, options) { + polymorphic_belongs_to: lambda { |entity, options| key = options.fetch(:as) - class_eval <<-RUBY, __FILE__, __LINE__ + 1 + class_eval <<~RUBY, __FILE__, __LINE__ + 1 def #{entity} return @_#{entity} if instance_variable_defined?('@_#{entity}') @_#{entity} = begin diff --git a/lib/hawk/model/base.rb b/lib/hawk/model/base.rb index aca7700..92b33c6 100644 --- a/lib/hawk/model/base.rb +++ b/lib/hawk/model/base.rb @@ -22,9 +22,9 @@ def initialize(attributes = {}, params = {}) end def inspect - attributes = schema.inject('') { |s, (k, v)| + attributes = schema.inject('') do |s, (k, _v)| s << " #{k}=#{read_attribute(k).inspect}" - } + end "#<#{self.class.name}#{attributes}>" end end diff --git a/lib/hawk/model/collection.rb b/lib/hawk/model/collection.rb index e945a95..dbe0b7a 100644 --- a/lib/hawk/model/collection.rb +++ b/lib/hawk/model/collection.rb @@ -2,7 +2,7 @@ module Hawk module Model class Collection < Array def initialize(elements = [], options = {}) - self.replace(elements) + replace(elements) @total_count = options[:total_count] @limit_value = options[:limit] @@ -13,14 +13,10 @@ def inspect "#<#{self.class.name} count:#{total_count} contents:#{super}>" end - attr_reader :total_count + attr_reader :total_count, :offset_value def limit_value - @limit_value or raise Hawk::Error, "This collection is not paginated" - end - - def offset_value - @offset_value + @limit_value or raise Hawk::Error, 'This collection is not paginated' end def count @@ -30,8 +26,8 @@ def count def map(&block) self.class.new(super, total_count: @total_count, - limit: @limit_value, - offset: @offset_value + limit: @limit_value, + offset: @offset_value ) end end diff --git a/lib/hawk/model/configurator.rb b/lib/hawk/model/configurator.rb index 85c9dd5..96733b4 100644 --- a/lib/hawk/model/configurator.rb +++ b/lib/hawk/model/configurator.rb @@ -8,7 +8,7 @@ def self.included(base) module ClassMethods def configure(&block) ([self] + configurable).each do |model| - model.instance_eval &block + model.instance_eval(&block) end end @@ -21,10 +21,10 @@ def inherited(subclass) protected def configurable - (@_configurable ||= []).inject(Set.new) { |s, klass| + (@_configurable ||= []).inject(Set.new) do |s, klass| s.add klass s.merge klass.configurable - }.to_a + end.to_a end end end diff --git a/lib/hawk/model/connection.rb b/lib/hawk/model/connection.rb index 9b41a16..bef2cd1 100644 --- a/lib/hawk/model/connection.rb +++ b/lib/hawk/model/connection.rb @@ -74,11 +74,11 @@ module ClassMethods def connection @_connection ||= begin raise Error::Configuration, "URL for #{name} is not yet set" unless url - raise Error::Configuration, "Please set the client_name" unless client_name + raise Error::Configuration, 'Please set the client_name' unless client_name - options = self.http_options.dup + options = http_options.dup headers = (options[:headers] ||= {}) - headers['User-Agent'] = self.client_name + headers['User-Agent'] = client_name Hawk::HTTP.new(url, options) end @@ -89,7 +89,7 @@ def url(url = nil) configurable.each { |model| model.url = @_url } - return @_url + @_url end alias url= url @@ -102,7 +102,7 @@ def http_options(options = nil) configurable.each { |model| model.http_options = @_http_options } - return @_http_options + @_http_options end alias http_options= http_options @@ -111,16 +111,16 @@ def client_name(name = nil) configurable.each { |model| model.client_name = @_client_name } - return @_client_name + @_client_name end alias client_name= client_name def inherited(subclass) super - subclass.url = self.url - subclass.http_options = self.http_options - subclass.client_name = self.client_name + subclass.url = url + subclass.http_options = http_options + subclass.client_name = client_name end end end diff --git a/lib/hawk/model/finder.rb b/lib/hawk/model/finder.rb index 5d79090..60db81c 100644 --- a/lib/hawk/model/finder.rb +++ b/lib/hawk/model/finder.rb @@ -6,7 +6,7 @@ def self.included(base) end def path_for(component, params = {}) - [self.class.model_path_from(params), self.id, component].compact.join('/') + [self.class.model_path_from(params), id, component].compact.join('/') end module ClassMethods @@ -67,8 +67,8 @@ def instantiate_many(repr, params) end collection_options = { - limit: params[limit_param], - offset: params[offset_param], + limit: params[limit_param], + offset: params[offset_param], total_count: total_count } @@ -76,7 +76,7 @@ def instantiate_many(repr, params) end def instantiate_one(repr, params) - if repr.key?(instance_key) && (repr[instance_key].is_a?(Hash)) + if repr.key?(instance_key) && repr[instance_key].is_a?(Hash) repr = repr.fetch(instance_key) end @@ -84,7 +84,7 @@ def instantiate_one(repr, params) end def instance_key - @_instance_key ||= self.name.demodulize.underscore + @_instance_key ||= name.demodulize.underscore end def collection_key @@ -126,7 +126,7 @@ def model_path(path = nil) end def default_model_path - self.name.demodulize.underscore.pluralize.freeze + name.demodulize.underscore.pluralize.freeze end def batch_path(path = nil) diff --git a/lib/hawk/model/lookup.rb b/lib/hawk/model/lookup.rb index efae5f8..287e682 100644 --- a/lib/hawk/model/lookup.rb +++ b/lib/hawk/model/lookup.rb @@ -38,13 +38,13 @@ def inherited(subclass) # # App::Post.model_class_for('Comment') # - # will return `App::Comment` + # will return +App::Comment+ # # while # # Client::Post.model_class_for('Comment') # - # will return `Client::Comment` + # will return +Client::Comment+ # # In a nutshell, first the model namespace is checked, # then the containing namespace, and then the inheritance @@ -89,8 +89,8 @@ def look_up_constant_in(name, scope) nil end - def cached_model_class_for(name, scope, &block) - @_class_cache[[name, scope.name]] ||= block.call + def cached_model_class_for(name, scope) + @_class_cache[[name, scope.name]] ||= yield end end end diff --git a/lib/hawk/model/pagination.rb b/lib/hawk/model/pagination.rb index 1b004a4..c80055d 100644 --- a/lib/hawk/model/pagination.rb +++ b/lib/hawk/model/pagination.rb @@ -12,7 +12,7 @@ def self.included(base) base.instance_eval do include Kaminari::ConfigurationMethods - eval <<-RUBY + eval <<-RUBY, binding, __FILE__, __LINE__ + 1 def #{Kaminari.config.page_method_name}(num = nil) limit(default_per_page). offset(default_per_page * ([num.to_i, 1].max - 1)) diff --git a/lib/hawk/model/proxy.rb b/lib/hawk/model/proxy.rb index e0d7d0a..81700b7 100644 --- a/lib/hawk/model/proxy.rb +++ b/lib/hawk/model/proxy.rb @@ -102,7 +102,7 @@ def method_missing(meth, *args, &block) end retval = klass.public_send(meth, *args, &block) - if retval.kind_of?(Proxy) + if retval.is_a?(Proxy) merge(retval) else retval diff --git a/lib/hawk/model/querying.rb b/lib/hawk/model/querying.rb index 20d030e..143221a 100644 --- a/lib/hawk/model/querying.rb +++ b/lib/hawk/model/querying.rb @@ -33,13 +33,13 @@ def default_params(params = nil) @_default_params ||= {} end - # Adds `limit` with the given number of records + # Adds +limit+ with the given number of records # def limit(n) where(limit_param => n) end - # Adds an `offset` with the given number of records + # Adds an +offset+ with the given number of records # def offset(n) where(offset_param => n) @@ -76,7 +76,7 @@ def first(params = {}) # {Hawk::Error::NotFound} if not found # def first!(params = {}) - first(params) or raise Hawk::Error::NotFound.new("Can't find first #{self}") + first(params) or raise(Hawk::Error::NotFound, "Can't find first #{self}") end alias find_by! first! end diff --git a/lib/hawk/model/schema.rb b/lib/hawk/model/schema.rb index d34e33e..9ad2be3 100644 --- a/lib/hawk/model/schema.rb +++ b/lib/hawk/model/schema.rb @@ -5,7 +5,7 @@ def self.included(base) base.extend ClassMethods end - def initialize(attributes = {}, params = {}) + def initialize(attributes = {}, _params = {}) cast!(attributes) # super not required, this is the last in the chain. end @@ -17,7 +17,7 @@ def attributes end alias to_h attributes - def as_json(*ignored) # FIXME + def as_json(*_ignored) # FIXME to_h end @@ -62,8 +62,8 @@ def schema(attributes = nil) module ClassMethods def inherited(subclass) super - subclass.instance_variable_set :@_schema, self.schema if self.schema - subclass.instance_variable_set :@_after_schema, self.after_schema if self.after_schema + subclass.instance_variable_set :@_schema, schema if schema + subclass.instance_variable_set :@_after_schema, after_schema if after_schema end def schema(&block) @@ -103,7 +103,7 @@ def define_schema_key(key, caster) read_attribute(key) end - define_method("#{key}=") do |value| + define_method(:"#{key}=") do |value| write_attribute(key, value) end @@ -122,7 +122,7 @@ def schema_type_of(attribute_name) def find_schema_caster_for(attribute) ATTRIBUTE_CASTS.each do |re, type| - if attribute =~ re + if attribute&.match?(re) return find_schema_caster_typed(type) end end @@ -148,7 +148,7 @@ def initialize(type, code) def call(value) @code.call(value) unless value.nil? - rescue => e + rescue StandardError => e "## Error while casting #{value} to #{type}: #{e.message} ##" end @@ -167,14 +167,14 @@ def to_s Caster.new(:datetime, ->(value) { Time.parse(value) }), Caster.new(:date, ->(value) { Date.parse(value) }), Caster.new(:bignum, ->(value) { BigDecimal(value) }), - Caster.new(:boolean, ->(value) { bools.include?(value) }), + Caster.new(:boolean, ->(value) { bools.include?(value) }) ].inject({}) { |h, c| h.update(c.type => c) } ATTRIBUTE_CASTS = { /_(?:at|from|until|on)$/ => :datetime, - /_date$/ => :date, - /_num$/ => :bignum, - /^is_/ => :boolean, + /_date$/ => :date, + /_num$/ => :bignum, + /^is_/ => :boolean } end end diff --git a/lib/hawk/model/schema/dsl.rb b/lib/hawk/model/schema/dsl.rb index 4ffa1ec..6aec33b 100644 --- a/lib/hawk/model/schema/dsl.rb +++ b/lib/hawk/model/schema/dsl.rb @@ -16,7 +16,7 @@ def each(&block) @types.each(&block) end - def method_missing(meth, *args, &block) + def method_missing(meth, *args) @types[meth] += args end end diff --git a/lib/hawk/model/scoping.rb b/lib/hawk/model/scoping.rb index e8616f1..37e4c5c 100644 --- a/lib/hawk/model/scoping.rb +++ b/lib/hawk/model/scoping.rb @@ -7,7 +7,7 @@ def self.included(base) module ClassMethods def scope(name, impl) - if self.respond_to?(name) + if respond_to?(name) raise Error::Configuration, "#{self.name} already has a #{name} singleton method defined" end diff --git a/lib/hawk/polyfills.rb b/lib/hawk/polyfills.rb index bdad196..331300f 100644 --- a/lib/hawk/polyfills.rb +++ b/lib/hawk/polyfills.rb @@ -3,7 +3,7 @@ module Polyfills def self.polyfill(klass, method, &impl) unless klass.instance_methods.include?(method) refine(klass) do - module_eval &impl + module_eval(&impl) end end end diff --git a/lib/hawk/rake/default_task.rb b/lib/hawk/rake/default_task.rb index 14d1197..8be5142 100644 --- a/lib/hawk/rake/default_task.rb +++ b/lib/hawk/rake/default_task.rb @@ -109,7 +109,7 @@ def invoke(task) # @return [nil] # def croak(msg) - $stderr.puts fancy(with_appraisal(msg)) + warn fancy(with_appraisal(msg)) end ## @@ -119,7 +119,7 @@ def croak(msg) # @raise [RuntimeError] # def bail(msg) - raise RuntimeError, fancy(msg) + raise fancy(msg).to_s end ## @@ -133,7 +133,7 @@ def with_appraisal(msg) msg = "%s \033[1;31m[%s]" % [msg, gemfile] end - return msg + msg end ## @@ -164,14 +164,14 @@ def gemfile # @return [Boolean] Are we running appraisals? # def running_appraisals? - ENV["APPRAISAL_INITIALIZED"] + ENV['APPRAISAL_INITIALIZED'] end ## # @return [Boolean] Are we running on CI? # def running_in_ci? - ENV["CI"] + ENV['CI'] end end end diff --git a/lib/hawk/rake/utils.rb b/lib/hawk/rake/utils.rb index 802f406..4ff0f44 100644 --- a/lib/hawk/rake/utils.rb +++ b/lib/hawk/rake/utils.rb @@ -9,10 +9,9 @@ module Utils ## # Captures the stdout emitted by the given +block+ # - # @param block [Proc] # @return [String] the captured output # - def capture_stdout(&block) + def capture_stdout stdout, string = $stdout, StringIO.new $stdout = string diff --git a/lib/hawk/version.rb b/lib/hawk/version.rb index 2b96cc1..0225460 100644 --- a/lib/hawk/version.rb +++ b/lib/hawk/version.rb @@ -1,3 +1,3 @@ module Hawk - VERSION = "2.0.0" + VERSION = '2.0.0' end