From 56e5e9700f8b8f7cd6193f777766561f27735753 Mon Sep 17 00:00:00 2001 From: Jean Luis Urena Date: Tue, 9 Jul 2024 16:42:38 -0400 Subject: [PATCH] [ISSUE-68] - Add linter, remove support ruby < 3.0 and rails < 6.1 --- .github/workflows/ruby.yml | 88 +++----------------- .standard.yml | 3 + Gemfile | 22 ++--- Rakefile | 4 +- cached_resource.gemspec | 26 +++--- lib/cached_resource.rb | 20 ++--- lib/cached_resource/cached_resource.rb | 6 +- lib/cached_resource/caching.rb | 41 ++++----- lib/cached_resource/configuration.rb | 30 ++++--- lib/cached_resource/version.rb | 2 +- spec/cached_resource/cached_resource_spec.rb | 38 ++++----- spec/cached_resource/caching_spec.rb | 32 +++---- spec/cached_resource/configuration_spec.rb | 42 ++++------ spec/support/matchers.rb | 16 ++-- 14 files changed, 148 insertions(+), 222 deletions(-) create mode 100644 .standard.yml diff --git a/.github/workflows/ruby.yml b/.github/workflows/ruby.yml index bc101b9..a9e2128 100644 --- a/.github/workflows/ruby.yml +++ b/.github/workflows/ruby.yml @@ -5,95 +5,25 @@ # This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake # For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby -name: Test +name: Code Coverage -on: [push] +on: [push, workflow_dispatch, pull_request] permissions: contents: read jobs: test: - runs-on: ubuntu-20.04 - strategy: matrix: - ruby-version: ['2.3', '2.4', '2.5', '2.6', '2.7', '3.0', '3.1', '3.2', '3.3'] - rails-version: ['4.2', '5.0', '5.1', '6.0', '6.1', '7.0', '7.1'] - exclude: - # activesupport (~> 6.0.0) was resolved to 6.0.6.1, which depends on ruby (>= 2.5.0) - # activesupport (~> 6.1.0) was resolved to 6.1.7.2, which depends on ruby (>= 2.5.0) - - ruby-version: '2.3' - rails-version: '6.0' - - ruby-version: '2.3' - rails-version: '6.1' - - ruby-version: '2.4' - rails-version: '6.0' - - ruby-version: '2.4' - rails-version: '6.1' - # activesupport (~> 7.0.0) was resolved to 7.0.4.2, which depends on Ruby (>= 2.7.0) - - ruby-version: '2.3' - rails-version: '7.0' - - ruby-version: '2.4' - rails-version: '7.0' - - ruby-version: '2.5' - rails-version: '7.0' - - ruby-version: '2.6' - rails-version: '7.0' - # incompatbility with BigDecimal.new - - ruby-version: '2.7' - rails-version: '4.2' - - ruby-version: '3.0' - rails-version: '4.2' - - ruby-version: '3.1' - rails-version: '4.2' - - ruby-version: '3.2' - rails-version: '4.2' - # ArgumentError: expected attributes to be able to convert to Hash, got "#" - # probably keyword argument delegation different in Ruby 3 - # https://www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/ - - ruby-version: '3.0' - rails-version: '5.0' - - ruby-version: '3.0' - rails-version: '5.1' - - ruby-version: '3.1' - rails-version: '5.0' - - ruby-version: '3.1' - rails-version: '5.1' - - ruby-version: '3.2' - rails-version: '5.0' - - ruby-version: '3.2' - rails-version: '5.1' - # rails (~> 7.1.0) was resolved to 7.1.3.2, which depends on Ruby (>= 2.7.0) - - ruby-version: '2.3' - rails-version: '7.1' - - ruby-version: '2.4' - rails-version: '7.1' - - ruby-version: '2.5' - rails-version: '7.1' - - ruby-version: '2.6' - rails-version: '7.1' - # Because rails >= 4.0.0.beta1, < 5.0.5.rc1 depends on bundler >= 1.3.0, < 2.0 - # and the current Bundler version (2.5.9) does not satisfy bundler >= 1.3.0, < 2.0, - # rails >= 4.0.0.beta1, < 5.0.5.rc1 cannot be used. - # So, because Gemfile depends on rails ~> 4.2.0, - # version solving has failed. - - ruby-version: '3.3' - rails-version: '4.2' - + rails-version: ["6.1", "7.1"] steps: - uses: actions/checkout@v4 - - name: Set up Ruby ${{ matrix.ruby-version }} - # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, - # change this to (see https://github.com/ruby/setup-ruby#versioning): - # uses: ruby/setup-ruby@v1 + - name: Set up Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: ${{ matrix.ruby-version }} - - name: Install bundler 1.x.x - if: matrix.rails-version == '4.2' - run: gem uninstall -aIx bundler && gem install bundler -v 1.17.3 + ruby-version: 3.0 - name: Install dependencies run: bundle install env: @@ -101,3 +31,11 @@ jobs: DEBUG: true - name: Run tests run: bundle exec rake + lint: + runs-on: ubuntu-20.04 + permissions: + checks: write + contents: write + steps: + - name: Standard Ruby + uses: standardrb/standard-ruby-action@v1 diff --git a/.standard.yml b/.standard.yml new file mode 100644 index 0000000..ed3d205 --- /dev/null +++ b/.standard.yml @@ -0,0 +1,3 @@ +fix: true +parallel: true +ruby_version: 3.0 \ No newline at end of file diff --git a/Gemfile b/Gemfile index 41ee41e..6cec6e3 100644 --- a/Gemfile +++ b/Gemfile @@ -5,27 +5,27 @@ gemspec def eval_gemfile(path) gemfile_local = File.expand_path(path, __FILE__) if File.readable?(gemfile_local) - puts "Loading #{gemfile_local}..." if ENV['DEBUG'] + puts "Loading #{gemfile_local}..." if ENV["DEBUG"] instance_eval(File.read(gemfile_local)) end end -puts "\e[93mUsing TEST_RAILS_VERSION #{ENV['TEST_RAILS_VERSION']}\e[0m" if ENV['DEBUG'] -case ENV['TEST_RAILS_VERSION'] +puts "\e[93mUsing TEST_RAILS_VERSION #{ENV["TEST_RAILS_VERSION"]}\e[0m" if ENV["DEBUG"] +case ENV["TEST_RAILS_VERSION"] when "4.2" - eval_gemfile('../gemfiles/4.2.gemfile') + eval_gemfile("../gemfiles/4.2.gemfile") when "5.0" - eval_gemfile('../gemfiles/5.0.gemfile') + eval_gemfile("../gemfiles/5.0.gemfile") when "5.1" - eval_gemfile('../gemfiles/5.1.gemfile') + eval_gemfile("../gemfiles/5.1.gemfile") when "6.0" - eval_gemfile('../gemfiles/6.0.gemfile') + eval_gemfile("../gemfiles/6.0.gemfile") when "6.1" - eval_gemfile('../gemfiles/6.1.gemfile') + eval_gemfile("../gemfiles/6.1.gemfile") when "7.0" - eval_gemfile('../gemfiles/7.0.gemfile') + eval_gemfile("../gemfiles/7.0.gemfile") when "7.1" - eval_gemfile('../gemfiles/7.1.gemfile') + eval_gemfile("../gemfiles/7.1.gemfile") else - puts "\e[93mNo TEST_RAILS_VERSION present, letting dependency manager decide what's best.\e[0m" if ENV['DEBUG'] + puts "\e[93mNo TEST_RAILS_VERSION present, letting dependency manager decide what's best.\e[0m" if ENV["DEBUG"] end diff --git a/Rakefile b/Rakefile index 8851c33..8f2b9cd 100644 --- a/Rakefile +++ b/Rakefile @@ -1,7 +1,7 @@ require "bundler/gem_tasks" -require 'rspec/core/rake_task' +require "rspec/core/rake_task" desc "Run all examples" RSpec::Core::RakeTask.new(:spec) -task :default => :spec +task default: :spec diff --git a/cached_resource.gemspec b/cached_resource.gemspec index db629ad..a7371ff 100644 --- a/cached_resource.gemspec +++ b/cached_resource.gemspec @@ -1,23 +1,21 @@ -# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "cached_resource/version" Gem::Specification.new do |s| - s.name = "cached_resource" - s.version = CachedResource::VERSION - s.authors = "Morgan Brown" - s.email = "cached_resource@email.mhgbrown.is" - s.homepage = "https://github.com/mhgbrown/cached_resource" - s.summary = %q{Caching for ActiveResource} - s.description = %q{Enables request-based caching for ActiveResource} - s.licenses = ["MIT"] + s.name = "cached_resource" + s.version = CachedResource::VERSION + s.authors = "Morgan Brown" + s.email = "cached_resource@email.mhgbrown.is" + s.homepage = "https://github.com/mhgbrown/cached_resource" + s.summary = "Caching for ActiveResource" + s.description = "Enables request-based caching for ActiveResource" + s.licenses = ["MIT"] - s.files = `git ls-files`.split("\n") - s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") - s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } + s.files = `git ls-files`.split("\n") + s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } s.require_paths = ["lib"] - s.required_ruby_version = ">= 1.9.0" + s.required_ruby_version = ">= 3.0" s.add_runtime_dependency "activeresource", ">= 4.0" s.add_runtime_dependency "activesupport", ">= 4.0" @@ -29,5 +27,5 @@ Gem::Specification.new do |s| s.add_development_dependency "rspec" s.add_development_dependency "simplecov", "~> 0.22.0" s.add_development_dependency "timecop", "~> 0.9.10" - + s.add_development_dependency "standard", "~> 1.39", ">= 1.39.1" end diff --git a/lib/cached_resource.rb b/lib/cached_resource.rb index d1f5db6..b3567a2 100644 --- a/lib/cached_resource.rb +++ b/lib/cached_resource.rb @@ -1,14 +1,14 @@ -require 'ostruct' +require "ostruct" -require 'nilio' -require 'active_support/cache' -require 'active_support/concern' -require 'active_support/logger' -require 'cached_resource/cached_resource' -require 'cached_resource/configuration' -require 'cached_resource/caching' -require 'cached_resource/version' -require 'active_resource' +require "nilio" +require "active_support/cache" +require "active_support/concern" +require "active_support/logger" +require "cached_resource/cached_resource" +require "cached_resource/configuration" +require "cached_resource/caching" +require "cached_resource/version" +require "active_resource" module CachedResource # nada diff --git a/lib/cached_resource/cached_resource.rb b/lib/cached_resource/cached_resource.rb index 99302fc..1733f84 100644 --- a/lib/cached_resource/cached_resource.rb +++ b/lib/cached_resource/cached_resource.rb @@ -10,7 +10,7 @@ class << self attr_accessor :cached_resource # Initialize cached resource or retrieve the current cached resource configuration. - def cached_resource(options={}) + def cached_resource(options = {}) defined?(@cached_resource) && @cached_resource || setup_cached_resource!(options) end @@ -20,7 +20,7 @@ def setup_cached_resource!(options) @cached_resource = CachedResource::Configuration.new(options) if @cached_resource.concurrent_write begin - require 'concurrent/promise' + require "concurrent/promise" rescue LoadError @cached_resource.logger.error( "`concurrent_write` option is enabled, but `concurrent-ruby` is not an installed dependency" @@ -40,7 +40,7 @@ module ClassMethods # that wants an independent configuration will need to execute: # self.cached_resource = CachedResource::Configuration.new(options={}) def inherited(child) - child.cached_resource = self.cached_resource if defined?(@cached_resource) + child.cached_resource = cached_resource if defined?(@cached_resource) super end end diff --git a/lib/cached_resource/caching.rb b/lib/cached_resource/caching.rb index 99207e4..b7ccacf 100644 --- a/lib/cached_resource/caching.rb +++ b/lib/cached_resource/caching.rb @@ -25,7 +25,7 @@ def find_with_cache(*arguments) end # Clear the cache. - def clear_cache(options=nil) + def clear_cache(options = nil) if cached_resource.concurrent_write Concurrent::Promise.execute { cache_clear(options) } else @@ -79,7 +79,9 @@ def update_collection_cache(updates, *arguments) collection = cache_read(cache_key(cached_resource.collection_arguments)) if collection && !updates.empty? - index = collection.inject({}) { |hash, object| hash[object.send(primary_key)] = object; hash } + index = collection.each_with_object({}) { |object, hash| + hash[object.send(primary_key)] = object + } updates.each { |object| index[object.send(primary_key)] = object } cache_write(cache_key(cached_resource.collection_arguments), index.values, *arguments) end @@ -100,13 +102,12 @@ def is_collection?(*arguments) # Determine if the given arguments represent # any collection of objects def is_any_collection?(*arguments) - cached_resource.collection_arguments.all?{ |arg| arguments.include?(arg) } || arguments.include?(:all) + cached_resource.collection_arguments.all? { |arg| arguments.include?(arg) } || arguments.include?(:all) end # Read a entry from the cache for the given key. def cache_read(key) object = cached_resource.cache.read(key).try do |json_cache| - json = ActiveSupport::JSON.decode(json_cache) unless json.nil? @@ -116,7 +117,7 @@ def cache_read(key) next restored unless respond_to?(:collection_parser) collection_parser.new(restored).tap do |parser| parser.resource_class = self - parser.original_params = json['original_params'].deep_symbolize_keys + parser.original_params = json["original_params"].deep_symbolize_keys end else full_dup(cache) @@ -141,15 +142,15 @@ def _cache_write(key, object, *arguments) params = options[:params] prefix_options, query_options = split_options(params) - result = cached_resource.cache.write(key, object_to_json(object, prefix_options, query_options), :race_condition_ttl => cached_resource.race_condition_ttl, :expires_in => cached_resource.generate_ttl) + result = cached_resource.cache.write(key, object_to_json(object, prefix_options, query_options), race_condition_ttl: cached_resource.race_condition_ttl, expires_in: cached_resource.generate_ttl) result && cached_resource.logger.info("#{CachedResource::Configuration::LOGGER_PREFIX} WRITE #{key}") result end # Clear the cache. - def cache_clear(options=nil) + def cache_clear(options = nil) # Memcache doesn't support delete_matched, which can also be computationally expensive - if cached_resource.cache.class.to_s == 'ActiveSupport::Cache::MemCacheStore' || options.try(:fetch,:all) + if (Object.const_defined?(:Dalli) && cached_resource.cache.class.instance_of?("ActiveSupport::Cache::MemCacheStore")) || options.try(:fetch, :all) cached_resource.cache.clear.tap do |result| cached_resource.logger.info("#{CachedResource::Configuration::LOGGER_PREFIX} CLEAR ALL") end @@ -171,13 +172,13 @@ def cache_key_delete_pattern # Generate the request cache key. def cache_key(*arguments) - "#{name_key}/#{arguments.join('/')}".downcase.delete(' ') + "#{name_key}/#{arguments.join("/")}".downcase.delete(" ") end def name_key @name_key ||= begin prefix = cached_resource.cache_key_prefix.nil? ? "" : "#{cached_resource.cache_key_prefix}/" - prefix + name.parameterize.gsub("-", "/") + prefix + name.parameterize.tr("-", "/") end end @@ -190,16 +191,16 @@ def full_dup(record) end def json_to_object(json) - resource = json['resource'] + resource = json["resource"] if resource.is_a? Array resource.map do |attrs| - self.new(attrs["object"], attrs["persistence"]).tap do |resource| - resource.prefix_options = json['prefix_options'] + new(attrs["object"], attrs["persistence"]).tap do |resource| + resource.prefix_options = json["prefix_options"] end end else - self.new(resource["object"], resource["persistence"]).tap do |resource| - resource.prefix_options = json['prefix_options'] + new(resource["object"], resource["persistence"]).tap do |resource| + resource.prefix_options = json["prefix_options"] end end end @@ -207,14 +208,14 @@ def json_to_object(json) def object_to_json(object, prefix_options, query_options) if object.is_a? Enumerable { - :resource => object.map { |o| { :object => o, :persistence => o.persisted? } }, - :prefix_options => prefix_options, - :original_params => query_options + resource: object.map { |o| {object: o, persistence: o.persisted?} }, + prefix_options: prefix_options, + original_params: query_options }.to_json else { - :resource => { :object => object, :persistence => object.persisted? }, - :prefix_options => prefix_options + resource: {object: object, persistence: object.persisted?}, + prefix_options: prefix_options }.to_json end end diff --git a/lib/cached_resource/configuration.rb b/lib/cached_resource/configuration.rb index 8f080b7..0dd0495 100644 --- a/lib/cached_resource/configuration.rb +++ b/lib/cached_resource/configuration.rb @@ -2,7 +2,6 @@ module CachedResource # The Configuration class manages class specific options # for cached resource. class Configuration < OpenStruct - # default or fallback cache without rails CACHE = ActiveSupport::Cache::MemoryStore.new @@ -25,20 +24,20 @@ class Configuration < OpenStruct # :logger, default: Rails.logger or ActiveSupport::Logger.new(NilIO.new), # :cache_collections, default: true # :concurrent_write, default: false - def initialize(options={}) + def initialize(options = {}) super({ - :cache => defined?(Rails.cache) && Rails.cache || CACHE, - :cache_collections => true, - :cache_key_prefix => nil, - :collection_arguments => [:all], - :collection_synchronize => false, - :concurrent_write => false, - :enabled => true, - :logger => defined?(Rails.logger) && Rails.logger || LOGGER, - :race_condition_ttl => 86400, - :ttl => 604800, - :ttl_randomization => false, - :ttl_randomization_scale => 1..2 + cache: defined?(Rails.cache) && Rails.cache || CACHE, + cache_collections: true, + cache_key_prefix: nil, + collection_arguments: [:all], + collection_synchronize: false, + concurrent_write: false, + enabled: true, + logger: defined?(Rails.logger) && Rails.logger || LOGGER, + race_condition_ttl: 86400, + ttl: 604800, + ttl_randomization: false, + ttl_randomization_scale: 1..2 }.merge(options)) end @@ -72,10 +71,9 @@ def randomized_ttl # Choose a random value from within the given range, optionally # seeded by seed. - def sample_range(range, seed=nil) + def sample_range(range, seed = nil) srand seed if seed rand * (range.end - range.begin) + range.begin end - end end diff --git a/lib/cached_resource/version.rb b/lib/cached_resource/version.rb index 3325b48..817d4f8 100644 --- a/lib/cached_resource/version.rb +++ b/lib/cached_resource/version.rb @@ -1,3 +1,3 @@ module CachedResource - VERSION = "8.0.0" + VERSION = '9.0.0' end diff --git a/spec/cached_resource/cached_resource_spec.rb b/spec/cached_resource/cached_resource_spec.rb index 666e126..3eddf45 100644 --- a/spec/cached_resource/cached_resource_spec.rb +++ b/spec/cached_resource/cached_resource_spec.rb @@ -1,17 +1,17 @@ -require 'spec_helper' +require "spec_helper" RSpec.describe CachedResource::Model do - let(:logger) { double(:Logger, error: nil)} + let(:logger) { double(:Logger, error: nil) } let(:dummy_class) do Class.new(ActiveResource::Base) do include CachedResource::Model end end - describe '.cached_resource' do - context 'when cached resource is not set up' do - it 'initializes and returns a new cached resource configuration' do - options = { logger: logger } + describe ".cached_resource" do + context "when cached resource is not set up" do + it "initializes and returns a new cached resource configuration" do + options = {logger: logger} allow(CachedResource::Configuration).to receive(:new).with(options).and_call_original cached_resource = dummy_class.cached_resource(options) @@ -22,8 +22,8 @@ end end - context 'when cached resource is already set up' do - it 'returns the existing cached resource configuration' do + context "when cached resource is already set up" do + it "returns the existing cached resource configuration" do existing_config = CachedResource::Configuration.new dummy_class.instance_variable_set(:@cached_resource, existing_config) @@ -34,9 +34,9 @@ end end - describe '.setup_cached_resource!' do - it 'creates a new cached resource configuration' do - options = { logger: logger } + describe ".setup_cached_resource!" do + it "creates a new cached resource configuration" do + options = {logger: logger} allow(CachedResource::Configuration).to receive(:new).with(options).and_call_original dummy_class.setup_cached_resource!(options) @@ -45,14 +45,14 @@ expect(CachedResource::Configuration).to have_received(:new).with(options) end - context 'when concurrent_write is enabled' do + context "when concurrent_write is enabled" do before do allow(CachedResource::Configuration).to receive(:new).and_return( double(concurrent_write: true, logger: logger) ) end - it 'requires concurrent/promise' do + it "requires concurrent/promise" do expect { dummy_class.setup_cached_resource!(concurrent_write: true) }.not_to raise_error(LoadError) end @@ -61,7 +61,7 @@ allow(dummy_class).to receive(:require).with("concurrent/promise").and_raise(LoadError) end - it 'requires concurrent/promise' do + it "requires concurrent/promise" do expect(logger).to receive(:error).with( "`concurrent_write` option is enabled, but `concurrent-ruby` is not an installed dependency" ).once @@ -71,11 +71,11 @@ end end - describe '.inherited' do + describe ".inherited" do let(:child_class) { Class.new(dummy_class) } - context 'when cached resource is defined in superclass' do - it 'copies the cached resource configuration to the subclass' do + context "when cached resource is defined in superclass" do + it "copies the cached resource configuration to the subclass" do existing_config = CachedResource::Configuration.new dummy_class.instance_variable_set(:@cached_resource, existing_config) @@ -83,8 +83,8 @@ end end - context 'when cached resource is not defined in superclass' do - it 'does not set cached resource configuration in the subclass' do + context "when cached resource is not defined in superclass" do + it "does not set cached resource configuration in the subclass" do expect(child_class.instance_variable_defined?(:@cached_resource)).to be_falsey end end diff --git a/spec/cached_resource/caching_spec.rb b/spec/cached_resource/caching_spec.rb index 640a8fe..54d74c2 100644 --- a/spec/cached_resource/caching_spec.rb +++ b/spec/cached_resource/caching_spec.rb @@ -1,4 +1,4 @@ -require 'spec_helper' +require "spec_helper" class Thing < ActiveResource::Base self.site = "http://api.thing.com" @@ -16,8 +16,8 @@ def read_from_cache(key, model = Thing) describe CachedResource::Caching do let(:thing) { {thing: {id: 1, name: "Ada"}} } - let(:thing_collection) { [{id: 1, name: "Ada"}, {id: 2, name: "Ada", major: 'CS'}] } - let(:thing_collection2) { [{id: 2, name: "Ada", major: 'CS'}] } + let(:thing_collection) { [{id: 1, name: "Ada"}, {id: 2, name: "Ada", major: "CS"}] } + let(:thing_collection2) { [{id: 2, name: "Ada", major: "CS"}] } let(:other_thing) { {thing: {id: 1, name: "Ari"}} } let(:thing2) { {thing: {id: 2, name: "Joe"}} } let(:other_thing2) { {thing: {id: 2, name: "Jeb"}} } @@ -56,7 +56,7 @@ def read_from_cache(key, model = Thing) end it "caches without whitespace in keys" do - result = Thing.find(1, from: 'path', params: { foo: 'bar' }) + result = Thing.find(1, from: "path", params: {foo: "bar"}) expect(read_from_cache('thing/1/{:from=>"path",:params=>{:foo=>"bar"}}')).to eq(result) end @@ -69,7 +69,7 @@ def read_from_cache(key, model = Thing) Thing.find(1) NotTheThing.find(1) expect { Thing.clear_cache }.to change { read_from_cache("thing/1") }.from(kind_of(Thing)).to(nil).and( - not_change { read_from_cache("notthething/1", NotTheThing) } + not_change { read_from_cache("notthething/1", NotTheThing) } ) end @@ -114,12 +114,12 @@ def read_from_cache(key, model = Thing) context "Caching a collection" do it "does not cache an empty array response" do - Thing.find(:all, params: { name: '43' }) + Thing.find(:all, params: {name: "43"}) expect(read_from_cache("thing/all/name/43")).to be_nil end it "does not cache a nil response" do - Thing.find(:all, params: { name: '42' }) + Thing.find(:all, params: {name: "42"}) expect(read_from_cache("thing/all/name/42")).to be_nil end @@ -132,7 +132,7 @@ def read_from_cache(key, model = Thing) Thing.all NotTheThing.all expect { Thing.clear_cache }.to change { read_from_cache("thing/all") }.from(kind_of(Enumerable)).to(nil).and( - not_change { read_from_cache("notthething/all", NotTheThing) } + not_change { read_from_cache("notthething/all", NotTheThing) } ) end @@ -173,7 +173,7 @@ def read_from_cache(key, model = Thing) end context "TTL" do - let(:now) { Time.new(1999,12,31, 12, 0, 0) } + let(:now) { Time.new(1999, 12, 31, 12, 0, 0) } before do Timecop.freeze(now) @@ -187,7 +187,7 @@ def read_from_cache(key, model = Thing) it "remakes the request when the ttl expires" do expect { Thing.find(1) }.to change { ActiveResource::HttpMock.requests.length }.from(0).to(1) - Timecop.travel(now + 2 ) + Timecop.travel(now + 2) expect { Thing.find(1) }.to change { ActiveResource::HttpMock.requests.length }.from(1).to(2) end end @@ -195,7 +195,7 @@ def read_from_cache(key, model = Thing) context "when concurrency is turned on" do before do ActiveResource::HttpMock.respond_to do |mock| - mock.get "/things/5.json", {}, { thing: { id: 1, name: ("x" * 1_000_000) } }.to_json + mock.get "/things/5.json", {}, {thing: {id: 1, name: ("x" * 1_000_000)}}.to_json end Thing.cached_resource.concurrent_write = true end @@ -221,7 +221,7 @@ def read_from_cache(key, model = Thing) context "when concurrency is turned on" do before do ActiveResource::HttpMock.respond_to do |mock| - mock.get "/things/5.json", {}, { thing: { id: 1, name: ("x" * 1_000_000) } }.to_json + mock.get "/things/5.json", {}, {thing: {id: 1, name: ("x" * 1_000_000)}}.to_json end Thing.cached_resource.concurrent_write = false end @@ -251,7 +251,7 @@ def read_from_cache(key, model = Thing) context "when ActiveSupport.parse_json_times is enabled" do before(:all) do - Time.zone = 'UTC' + Time.zone = "UTC" ActiveSupport.parse_json_times = true end @@ -277,7 +277,7 @@ def read_from_cache(key, model = Thing) end it "should rewrite cache entries for its members when reloaded" do - old_results = Thing.all(:reload => true) + old_results = Thing.all(reload: true) # Update response ActiveResource::HttpMock.respond_to do |mock| mock.get "/things/1.json", {}, other_thing.to_json @@ -310,12 +310,12 @@ def read_from_cache(key, model = Thing) end it "does not cache a nil response" do - Thing.find(:all, params: { name: '42' }) + Thing.find(:all, params: {name: "42"}) expect(read_from_cache("thing/all/name/42")).to be_nil end it "does not cache an empty array response" do - Thing.find(:all, params: { name: '43' }) + Thing.find(:all, params: {name: "43"}) expect(read_from_cache("thing/all/name/43")).to be_nil end end diff --git a/spec/cached_resource/configuration_spec.rb b/spec/cached_resource/configuration_spec.rb index 2e1b157..a0826be 100644 --- a/spec/cached_resource/configuration_spec.rb +++ b/spec/cached_resource/configuration_spec.rb @@ -1,29 +1,29 @@ -require 'spec_helper' +require "spec_helper" class Foo < ActiveResource::Base cached_resource end class Bar < ActiveResource::Base - cached_resource :ttl => 1, - :race_condition_ttl => 5, - :cache => "cache", - :logger => "logger", - :enabled => false, - :collection_synchronize => true, - :collection_arguments => [:every], - :custom => "irrelevant", - :cache_collections => true + cached_resource ttl: 1, + race_condition_ttl: 5, + cache: "cache", + logger: "logger", + enabled: false, + collection_synchronize: true, + collection_arguments: [:every], + custom: "irrelevant", + cache_collections: true end class Bar2 < Bar; end + class Bar3 < Bar # override the superclasses configuration - self.cached_resource = CachedResource::Configuration.new(:ttl => 60) + self.cached_resource = CachedResource::Configuration.new(ttl: 60) end describe CachedResource::Configuration do - let(:configuration) { described_class.new } let(:default_logger) { defined?(ActiveSupport::Logger) ? ActiveSupport::Logger : ActiveSupport::BufferedLogger } @@ -73,9 +73,9 @@ class Bar3 < Bar expect(configuration.logger.class).to eq(default_logger) # ActiveSupport switched around the log destination variables # Check if either are what we expect to be compatible - old_as = configuration.logger.instance_variable_get(:@log).class == NilIO - new_as = configuration.logger.instance_variable_get(:@log_dest).class == NilIO - newer_as = configuration.logger.instance_variable_get(:@logdev).instance_variable_get(:@dev).class == NilIO + old_as = configuration.logger.instance_variable_get(:@log).instance_of?(NilIO) + new_as = configuration.logger.instance_variable_get(:@log_dest).instance_of?(NilIO) + newer_as = configuration.logger.instance_variable_get(:@logdev).instance_variable_get(:@dev).instance_of?(NilIO) expect(old_as || new_as || newer_as).to eq(true) end @@ -86,16 +86,7 @@ class Bar3 < Bar describe "inside a Rails environment" do before(:each) do - Rails = OpenStruct.new(:logger => "logger", :cache => "cache") - load "cached_resource/configuration.rb" - end - - after(:each) do - # remove the rails constant and unbind the - # cache and logger from the configuration - # defaults - Object.send(:remove_const, :Rails) - load "cached_resource/configuration.rb" + stub_const("Rails", double(:Rails, logger: "logger", cache: "cache")) end it "should be logging to the rails logger" do @@ -150,7 +141,6 @@ class Bar3 < Bar expect(cr.cache_collections).to eq(true) expect(cr.race_condition_ttl).to eq(86400) end - end # At the moment, not too keen on implementing some fancy diff --git a/spec/support/matchers.rb b/spec/support/matchers.rb index d4f6d03..950129e 100644 --- a/spec/support/matchers.rb +++ b/spec/support/matchers.rb @@ -1,4 +1,4 @@ -require 'timeout' +require "timeout" RSpec::Matchers.define :eventually do |expected_matcher| supports_block_expectations @@ -8,16 +8,14 @@ end match do |actual| - begin - Timeout.timeout(@timeout_duration || 5) do - until expected_matcher.matches?(actual.call) - sleep 0.5 - end - true + Timeout.timeout(@timeout_duration || 5) do + until expected_matcher.matches?(actual.call) + sleep 0.5 end - rescue Timeout::Error - false + true end + rescue Timeout::Error + false end description do