├── test
├── dummy
│ ├── log
│ │ └── .keep
│ ├── lib
│ │ └── assets
│ │ │ └── .keep
│ ├── public
│ │ ├── favicon.ico
│ │ ├── apple-touch-icon.png
│ │ ├── apple-touch-icon-precomposed.png
│ │ ├── 500.html
│ │ ├── 422.html
│ │ └── 404.html
│ ├── app
│ │ ├── assets
│ │ │ ├── images
│ │ │ │ └── .keep
│ │ │ ├── config
│ │ │ │ └── manifest.js
│ │ │ └── stylesheets
│ │ │ │ └── application.css
│ │ ├── models
│ │ │ ├── concerns
│ │ │ │ └── .keep
│ │ │ ├── application_record.rb
│ │ │ ├── comment.rb
│ │ │ └── user.rb
│ │ ├── controllers
│ │ │ ├── concerns
│ │ │ │ └── .keep
│ │ │ └── application_controller.rb
│ │ ├── views
│ │ │ └── layouts
│ │ │ │ ├── mailer.text.erb
│ │ │ │ ├── mailer.html.erb
│ │ │ │ └── application.html.erb
│ │ ├── helpers
│ │ │ └── application_helper.rb
│ │ ├── channels
│ │ │ └── application_cable
│ │ │ │ ├── channel.rb
│ │ │ │ └── connection.rb
│ │ ├── mailers
│ │ │ └── application_mailer.rb
│ │ ├── jobs
│ │ │ └── application_job.rb
│ │ └── javascript
│ │ │ └── packs
│ │ │ └── application.js
│ ├── bin
│ │ ├── rake
│ │ ├── rails
│ │ └── setup
│ ├── config
│ │ ├── environment.rb
│ │ ├── routes.rb
│ │ ├── initializers
│ │ │ ├── mime_types.rb
│ │ │ ├── application_controller_renderer.rb
│ │ │ ├── cookies_serializer.rb
│ │ │ ├── filter_parameter_logging.rb
│ │ │ ├── permissions_policy.rb
│ │ │ ├── assets.rb
│ │ │ ├── wrap_parameters.rb
│ │ │ ├── backtrace_silencers.rb
│ │ │ ├── inflections.rb
│ │ │ └── content_security_policy.rb
│ │ ├── cable.yml
│ │ ├── boot.rb
│ │ ├── database.yml
│ │ ├── application.rb
│ │ ├── locales
│ │ │ └── en.yml
│ │ ├── storage.yml
│ │ ├── puma.rb
│ │ └── environments
│ │ │ ├── test.rb
│ │ │ ├── development.rb
│ │ │ └── production.rb
│ ├── config.ru
│ ├── Rakefile
│ └── db
│ │ ├── migrate
│ │ ├── 20210622192728_create_comments.rb
│ │ └── 20210622192311_create_users.rb
│ │ └── schema.rb
├── test_helper.rb
└── rails_cached_method_test.rb
├── lib
├── rails_cached_method
│ ├── version.rb
│ └── railtie.rb
├── tasks
│ └── rails_cached_method_tasks.rake
└── rails_cached_method.rb
├── docs
└── rails_cached_method.png
├── CHANGELOG.md
├── bin
└── test
├── .gitignore
├── Rakefile
├── Gemfile
├── rails_cached_method.gemspec
├── MIT-LICENSE
├── Gemfile.lock
└── README.md
/test/dummy/log/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/lib/assets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/app/assets/images/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/app/models/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/public/apple-touch-icon-precomposed.png:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/test/dummy/app/views/layouts/mailer.text.erb:
--------------------------------------------------------------------------------
1 | <%= yield %>
2 |
--------------------------------------------------------------------------------
/test/dummy/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/lib/rails_cached_method/version.rb:
--------------------------------------------------------------------------------
1 | module RailsCachedMethod
2 | VERSION = '0.1.1'
3 | end
4 |
--------------------------------------------------------------------------------
/test/dummy/app/assets/config/manifest.js:
--------------------------------------------------------------------------------
1 | //= link_tree ../images
2 | //= link_directory ../stylesheets .css
3 |
--------------------------------------------------------------------------------
/test/dummy/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 | end
3 |
--------------------------------------------------------------------------------
/lib/rails_cached_method/railtie.rb:
--------------------------------------------------------------------------------
1 | module RailsCachedMethod
2 | class Railtie < ::Rails::Railtie
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/docs/rails_cached_method.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/igorkasyanchuk/rails_cached_method/HEAD/docs/rails_cached_method.png
--------------------------------------------------------------------------------
/test/dummy/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative "../config/boot"
3 | require "rake"
4 | Rake.application.run
5 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | - 0.1.1
2 | Removed warning of redefining methods in CachedProxy class.
3 |
4 | - 0.1.0
5 | Initial release.
--------------------------------------------------------------------------------
/test/dummy/app/models/application_record.rb:
--------------------------------------------------------------------------------
1 | class ApplicationRecord < ActiveRecord::Base
2 | self.abstract_class = true
3 | end
4 |
--------------------------------------------------------------------------------
/bin/test:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | $: << File.expand_path("../test", __dir__)
3 |
4 | require "bundler/setup"
5 | require "rails/plugin/test"
6 |
--------------------------------------------------------------------------------
/test/dummy/app/channels/application_cable/channel.rb:
--------------------------------------------------------------------------------
1 | module ApplicationCable
2 | class Channel < ActionCable::Channel::Base
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/lib/tasks/rails_cached_method_tasks.rake:
--------------------------------------------------------------------------------
1 | # desc "Explaining what the task does"
2 | # task :rails_cached_method do
3 | # # Task goes here
4 | # end
5 |
--------------------------------------------------------------------------------
/test/dummy/app/channels/application_cable/connection.rb:
--------------------------------------------------------------------------------
1 | module ApplicationCable
2 | class Connection < ActionCable::Connection::Base
3 | end
4 | end
5 |
--------------------------------------------------------------------------------
/test/dummy/app/mailers/application_mailer.rb:
--------------------------------------------------------------------------------
1 | class ApplicationMailer < ActionMailer::Base
2 | default from: 'from@example.com'
3 | layout 'mailer'
4 | end
5 |
--------------------------------------------------------------------------------
/test/dummy/app/models/comment.rb:
--------------------------------------------------------------------------------
1 | class Comment < ApplicationRecord
2 | belongs_to :user
3 |
4 | def Comment.find_maximum_age
5 | 'n/a'
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/test/dummy/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | APP_PATH = File.expand_path('../config/application', __dir__)
3 | require_relative "../config/boot"
4 | require "rails/commands"
5 |
--------------------------------------------------------------------------------
/test/dummy/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require_relative "application"
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/test/dummy/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
3 | end
4 |
--------------------------------------------------------------------------------
/test/dummy/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require_relative "config/environment"
4 |
5 | run Rails.application
6 | Rails.application.load_server
7 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 |
--------------------------------------------------------------------------------
/test/dummy/app/models/user.rb:
--------------------------------------------------------------------------------
1 | class User < ApplicationRecord
2 | has_many :comments
3 |
4 | def User.find_maximum_age
5 | self.maximum(:age)
6 | end
7 |
8 | def last_comment
9 | comments.last
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.bundle/
2 | /doc/
3 | /log/*.log
4 | /pkg/
5 | /tmp/
6 | /test/dummy/db/*.sqlite3
7 | /test/dummy/db/*.sqlite3-*
8 | /test/dummy/log/*.log
9 | /test/dummy/storage/
10 | /test/dummy/tmp/
11 | .byebug_history
12 |
13 | *.gem
--------------------------------------------------------------------------------
/test/dummy/config/cable.yml:
--------------------------------------------------------------------------------
1 | development:
2 | adapter: async
3 |
4 | test:
5 | adapter: test
6 |
7 | production:
8 | adapter: redis
9 | url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
10 | channel_prefix: dummy_production
11 |
--------------------------------------------------------------------------------
/test/dummy/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require_relative "config/application"
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/test/dummy/config/boot.rb:
--------------------------------------------------------------------------------
1 | # Set up gems listed in the Gemfile.
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__)
3 |
4 | require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"])
5 | $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
6 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | require "bundler/setup"
2 |
3 | require "bundler/gem_tasks"
4 |
5 | require "rake/testtask"
6 |
7 | Rake::TestTask.new(:test) do |t|
8 | t.libs << 'test'
9 | t.pattern = 'test/**/*_test.rb'
10 | t.verbose = false
11 | end
12 |
13 | task default: :test
14 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/application_controller_renderer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # ActiveSupport::Reloader.to_prepare do
4 | # ApplicationController.renderer.defaults.merge!(
5 | # http_host: 'example.org',
6 | # https: false
7 | # )
8 | # end
9 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Specify a serializer for the signed and encrypted cookie jars.
4 | # Valid options are :json, :marshal, and :hybrid.
5 | Rails.application.config.action_dispatch.cookies_serializer = :json
6 |
--------------------------------------------------------------------------------
/test/dummy/app/jobs/application_job.rb:
--------------------------------------------------------------------------------
1 | class ApplicationJob < ActiveJob::Base
2 | # Automatically retry jobs that encountered a deadlock
3 | # retry_on ActiveRecord::Deadlocked
4 |
5 | # Most jobs are safe to ignore if the underlying records are no longer available
6 | # discard_on ActiveJob::DeserializationError
7 | end
8 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" }
3 |
4 | # Specify your gem's dependencies in rails_cached_method.gemspec.
5 | gemspec
6 |
7 | group :development do
8 | gem 'sqlite3'
9 | end
10 |
11 | # To use a debugger
12 | gem 'pry', group: [:development, :test]
13 |
--------------------------------------------------------------------------------
/test/dummy/app/views/layouts/mailer.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
10 |
11 | <%= yield %>
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [
5 | :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
6 | ]
7 |
--------------------------------------------------------------------------------
/test/dummy/db/migrate/20210622192728_create_comments.rb:
--------------------------------------------------------------------------------
1 | class CreateComments < ActiveRecord::Migration[6.1]
2 | def change
3 | create_table :comments do |t|
4 | t.integer :user_id
5 | t.text :message
6 |
7 | t.timestamps
8 | end
9 |
10 | 100.times do |i|
11 | User.all.sample.comments.create(message: "this is comment #{i}")
12 | end
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/test/dummy/app/views/layouts/application.html.erb:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Dummy
5 |
6 | <%= csrf_meta_tags %>
7 | <%= csp_meta_tag %>
8 |
9 | <%= stylesheet_link_tag 'application', media: 'all' %>
10 |
11 |
12 |
13 | <%= yield %>
14 |
15 |
16 |
--------------------------------------------------------------------------------
/test/dummy/db/migrate/20210622192311_create_users.rb:
--------------------------------------------------------------------------------
1 | class CreateUsers < ActiveRecord::Migration[6.1]
2 | def change
3 | create_table :users do |t|
4 | t.string :name
5 | t.integer :age
6 |
7 | t.timestamps
8 | end
9 |
10 | 50.times do |i|
11 | User.create(name: ["John", "Bob", "Alisa", "Michael", "Zena", "Xena"].sample + " #{i}", age: rand(100))
12 | end
13 | end
14 | end
15 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/permissions_policy.rb:
--------------------------------------------------------------------------------
1 | # Define an application-wide HTTP permissions policy. For further
2 | # information see https://developers.google.com/web/updates/2018/06/feature-policy
3 | #
4 | # Rails.application.config.permissions_policy do |f|
5 | # f.camera :none
6 | # f.gyroscope :none
7 | # f.microphone :none
8 | # f.usb :none
9 | # f.fullscreen :self
10 | # f.payment :self, "https://secure.example.com"
11 | # end
12 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/assets.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Version of your assets, change this if you want to expire all your assets.
4 | Rails.application.config.assets.version = '1.0'
5 |
6 | # Add additional assets to the asset load path.
7 | # Rails.application.config.assets.paths << Emoji.images_path
8 |
9 | # Precompile additional assets.
10 | # application.js, application.css, and all non-JS/CSS in the app/assets
11 | # folder are already added.
12 | # Rails.application.config.assets.precompile += %w( admin.js admin.css )
13 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json]
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code
7 | # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'".
8 | Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
9 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/test/dummy/config/database.yml:
--------------------------------------------------------------------------------
1 | # SQLite. Versions 3.8.0 and up are supported.
2 | # gem install sqlite3
3 | #
4 | # Ensure the SQLite 3 gem is defined in your Gemfile
5 | # gem 'sqlite3'
6 | #
7 | default: &default
8 | adapter: sqlite3
9 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
10 | timeout: 5000
11 |
12 | development:
13 | <<: *default
14 | database: db/development.sqlite3
15 |
16 | # Warning: The database defined as "test" will be erased and
17 | # re-generated from your development database when you run "rake".
18 | # Do not set this db to the same as development or production.
19 | test:
20 | <<: *default
21 | database: db/test.sqlite3
22 |
23 | production:
24 | <<: *default
25 | database: db/production.sqlite3
26 |
--------------------------------------------------------------------------------
/test/test_helper.rb:
--------------------------------------------------------------------------------
1 | # Configure Rails Environment
2 | ENV["RAILS_ENV"] = "test"
3 |
4 | require_relative "../test/dummy/config/environment"
5 | ActiveRecord::Migrator.migrations_paths = [File.expand_path("../test/dummy/db/migrate", __dir__)]
6 | require "rails/test_help"
7 |
8 | Rails.cache.clear
9 |
10 | require "rails/test_unit/reporter"
11 | Rails::TestUnitReporter.executable = 'bin/test'
12 |
13 | # Load fixtures from the engine
14 | if ActiveSupport::TestCase.respond_to?(:fixture_path=)
15 | ActiveSupport::TestCase.fixture_path = File.expand_path("fixtures", __dir__)
16 | ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
17 | ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files"
18 | ActiveSupport::TestCase.fixtures :all
19 | end
20 |
--------------------------------------------------------------------------------
/rails_cached_method.gemspec:
--------------------------------------------------------------------------------
1 | require_relative "lib/rails_cached_method/version"
2 |
3 | Gem::Specification.new do |spec|
4 | spec.name = "rails_cached_method"
5 | spec.version = RailsCachedMethod::VERSION
6 | spec.authors = ["Igor Kasyanchuk"]
7 | spec.email = ["igorkasyanchuk@gmail.com"]
8 | spec.homepage = "http://github.com/igorkasyanchuk/rails_cached_method"
9 | spec.summary = "Very easy way to cache results of your methods"
10 | spec.description = "Very easy way to cache results of your methods"
11 | spec.license = "MIT"
12 |
13 | spec.metadata["homepage_uri"] = spec.homepage
14 |
15 | spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"]
16 |
17 | spec.add_dependency "rails"
18 | spec.add_development_dependency "pry"
19 | end
20 |
--------------------------------------------------------------------------------
/test/dummy/app/javascript/packs/application.js:
--------------------------------------------------------------------------------
1 | // This is a manifest file that'll be compiled into application.js, which will include all the files
2 | // listed below.
3 | //
4 | // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
5 | // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
6 | //
7 | // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
8 | // compiled file. JavaScript code in this file should be added after the last require_* statement.
9 | //
10 | // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
11 | // about supported directives.
12 | //
13 | //= require rails-ujs
14 | //= require activestorage
15 | //= require_tree .
16 |
--------------------------------------------------------------------------------
/test/dummy/app/assets/stylesheets/application.css:
--------------------------------------------------------------------------------
1 | /*
2 | * This is a manifest file that'll be compiled into application.css, which will include all the files
3 | * listed below.
4 | *
5 | * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6 | * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7 | *
8 | * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9 | * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10 | * files in this directory. Styles in this file should be added after the last require_* statement.
11 | * It is generally better to create a new file per style scope.
12 | *
13 | *= require_tree .
14 | *= require_self
15 | */
16 |
--------------------------------------------------------------------------------
/test/dummy/config/application.rb:
--------------------------------------------------------------------------------
1 | require_relative "boot"
2 |
3 | require "rails/all"
4 |
5 | # Require the gems listed in Gemfile, including any gems
6 | # you've limited to :test, :development, or :production.
7 | Bundler.require(*Rails.groups)
8 | require "rails_cached_method"
9 |
10 | module Dummy
11 | class Application < Rails::Application
12 | config.load_defaults Rails::VERSION::STRING.to_f
13 |
14 | # Configuration for the application, engines, and railties goes here.
15 | #
16 | # These settings can be overridden in specific environments using the files
17 | # in config/environments, which are processed later.
18 | #
19 | # config.time_zone = "Central Time (US & Canada)"
20 | # config.eager_load_paths << Rails.root.join("extras")
21 | end
22 | end
23 |
24 | puts "===" * 20
25 | puts "===" * 20
26 | puts "ATTENTION: CACHING IS ENABLED IN DEV MODE IN CONFIGS!!!"
27 | puts "===" * 20
28 | puts "===" * 20
--------------------------------------------------------------------------------
/test/dummy/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # The following keys must be escaped otherwise they will not be retrieved by
20 | # the default I18n backend:
21 | #
22 | # true, false, on, off, yes, no
23 | #
24 | # Instead, surround them with single quotes.
25 | #
26 | # en:
27 | # 'true': 'foo'
28 | #
29 | # To learn more, please read the Rails Internationalization guide
30 | # available at https://guides.rubyonrails.org/i18n.html.
31 |
32 | en:
33 | hello: "Hello world"
34 |
--------------------------------------------------------------------------------
/MIT-LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2021 Igor Kasyanchuk
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining
4 | a copy of this software and associated documentation files (the
5 | "Software"), to deal in the Software without restriction, including
6 | without limitation the rights to use, copy, modify, merge, publish,
7 | distribute, sublicense, and/or sell copies of the Software, and to
8 | permit persons to whom the Software is furnished to do so, subject to
9 | the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be
12 | included in all copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 |
--------------------------------------------------------------------------------
/test/dummy/bin/setup:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require "fileutils"
3 |
4 | # path to your application root.
5 | APP_ROOT = File.expand_path('..', __dir__)
6 |
7 | def system!(*args)
8 | system(*args) || abort("\n== Command #{args} failed ==")
9 | end
10 |
11 | FileUtils.chdir APP_ROOT do
12 | # This script is a way to set up or update your development environment automatically.
13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome.
14 | # Add necessary setup steps to this file.
15 |
16 | puts '== Installing dependencies =='
17 | system! 'gem install bundler --conservative'
18 | system('bundle check') || system!('bundle install')
19 |
20 | # puts "\n== Copying sample files =="
21 | # unless File.exist?('config/database.yml')
22 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml'
23 | # end
24 |
25 | puts "\n== Preparing database =="
26 | system! 'bin/rails db:prepare'
27 |
28 | puts "\n== Removing old logs and tempfiles =="
29 | system! 'bin/rails log:clear tmp:clear'
30 |
31 | puts "\n== Restarting application server =="
32 | system! 'bin/rails restart'
33 | end
34 |
--------------------------------------------------------------------------------
/test/dummy/config/storage.yml:
--------------------------------------------------------------------------------
1 | test:
2 | service: Disk
3 | root: <%= Rails.root.join("tmp/storage") %>
4 |
5 | local:
6 | service: Disk
7 | root: <%= Rails.root.join("storage") %>
8 |
9 | # Use rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key)
10 | # amazon:
11 | # service: S3
12 | # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
13 | # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
14 | # region: us-east-1
15 | # bucket: your_own_bucket
16 |
17 | # Remember not to checkin your GCS keyfile to a repository
18 | # google:
19 | # service: GCS
20 | # project: your_project
21 | # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %>
22 | # bucket: your_own_bucket
23 |
24 | # Use rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key)
25 | # microsoft:
26 | # service: AzureStorage
27 | # storage_account_name: your_account_name
28 | # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %>
29 | # container: your_container_name
30 |
31 | # mirror:
32 | # service: Mirror
33 | # primary: local
34 | # mirrors: [ amazon, google, microsoft ]
35 |
--------------------------------------------------------------------------------
/test/dummy/db/schema.rb:
--------------------------------------------------------------------------------
1 | # This file is auto-generated from the current state of the database. Instead
2 | # of editing this file, please use the migrations feature of Active Record to
3 | # incrementally modify your database, and then regenerate this schema definition.
4 | #
5 | # This file is the source Rails uses to define your schema when running `bin/rails
6 | # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
7 | # be faster and is potentially less error prone than running all of your
8 | # migrations from scratch. Old migrations may fail to apply correctly if those
9 | # migrations use external dependencies or application code.
10 | #
11 | # It's strongly recommended that you check this file into your version control system.
12 |
13 | ActiveRecord::Schema.define(version: 2021_06_22_192728) do
14 |
15 | create_table "comments", force: :cascade do |t|
16 | t.integer "user_id"
17 | t.text "message"
18 | t.datetime "created_at", precision: 6, null: false
19 | t.datetime "updated_at", precision: 6, null: false
20 | end
21 |
22 | create_table "users", force: :cascade do |t|
23 | t.string "name"
24 | t.integer "age"
25 | t.datetime "created_at", precision: 6, null: false
26 | t.datetime "updated_at", precision: 6, null: false
27 | end
28 |
29 | end
30 |
--------------------------------------------------------------------------------
/test/dummy/config/initializers/content_security_policy.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Define an application-wide content security policy
4 | # For further information see the following documentation
5 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
6 |
7 | # Rails.application.config.content_security_policy do |policy|
8 | # policy.default_src :self, :https
9 | # policy.font_src :self, :https, :data
10 | # policy.img_src :self, :https, :data
11 | # policy.object_src :none
12 | # policy.script_src :self, :https
13 | # policy.style_src :self, :https
14 |
15 | # # Specify URI for violation reports
16 | # # policy.report_uri "/csp-violation-report-endpoint"
17 | # end
18 |
19 | # If you are using UJS then enable automatic nonce generation
20 | # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
21 |
22 | # Set the nonce only to specific directives
23 | # Rails.application.config.content_security_policy_nonce_directives = %w(script-src)
24 |
25 | # Report CSP violations to a specified URI
26 | # For further information see the following documentation:
27 | # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only
28 | # Rails.application.config.content_security_policy_report_only = true
29 |
--------------------------------------------------------------------------------
/test/dummy/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/test/dummy/config/puma.rb:
--------------------------------------------------------------------------------
1 | # Puma can serve each request in a thread from an internal thread pool.
2 | # The `threads` method setting takes two numbers: a minimum and maximum.
3 | # Any libraries that use thread pools should be configured to match
4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum
5 | # and maximum; this matches the default thread size of Active Record.
6 | #
7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
9 | threads min_threads_count, max_threads_count
10 |
11 | # Specifies the `worker_timeout` threshold that Puma will use to wait before
12 | # terminating a worker in development environments.
13 | #
14 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development"
15 |
16 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000.
17 | #
18 | port ENV.fetch("PORT") { 3000 }
19 |
20 | # Specifies the `environment` that Puma will run in.
21 | #
22 | environment ENV.fetch("RAILS_ENV") { "development" }
23 |
24 | # Specifies the `pidfile` that Puma will use.
25 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
26 |
27 | # Specifies the number of `workers` to boot in clustered mode.
28 | # Workers are forked web server processes. If using threads and workers together
29 | # the concurrency of the application would be max `threads` * `workers`.
30 | # Workers do not work on JRuby or Windows (both of which do not support
31 | # processes).
32 | #
33 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 }
34 |
35 | # Use the `preload_app!` method when specifying a `workers` number.
36 | # This directive tells Puma to first boot the application and load code
37 | # before forking the application. This takes advantage of Copy On Write
38 | # process behavior so workers use less memory.
39 | #
40 | # preload_app!
41 |
42 | # Allow puma to be restarted by `rails restart` command.
43 | plugin :tmp_restart
44 |
--------------------------------------------------------------------------------
/test/dummy/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/test/dummy/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/lib/rails_cached_method.rb:
--------------------------------------------------------------------------------
1 | require "rails_cached_method/version"
2 | require "rails_cached_method/railtie"
3 |
4 | module RailsCachedMethod
5 | class CachedProxy
6 | # disable warning of redefining __send__ and __object_id__
7 | old = $VERBOSE.dup
8 | $VERBOSE = nil
9 | Object.methods.each do |e|
10 | delegate e, to: :@__object__
11 | end
12 | $VERBOSE = old
13 |
14 | def initialize(object, key: nil, expires_in:, parent_key: nil, recache: false)
15 | @__object__ = object
16 | @__key__ = key
17 | @__expires_in__ = expires_in
18 | @__recache__ = recache
19 | @__parent_key__ = parent_key
20 | @__object__
21 | end
22 |
23 | def __value__
24 | @__object__
25 | end
26 |
27 | def method_missing(*args)
28 | key = ___compose_key__(args)
29 | if @__recache__
30 | #puts "deleting: #{key}"
31 | Rails.cache.delete(key)
32 | end
33 | #puts "key: #{key}, expires_in: #{@__expires_in__}, args: #{args}, recache: #{@__recache__}"
34 | Rails.cache.fetch(key, expires_in: @__expires_in__) do
35 | CachedProxy.new(
36 | @__object__.send(*args),
37 | expires_in: @__expires_in__,
38 | recache: @__recache__,
39 | parent_key: key,
40 | )
41 | end
42 | end
43 |
44 | private
45 | def ___compose_key__(args)
46 | result = [@__parent_key__, @__key__]
47 | result += if @__object__.respond_to?(:to_global_id)
48 | [@__object__.to_global_id]
49 | elsif @__object__.is_a?(ActiveRecord::Relation)
50 | [@__object__.class]
51 | else
52 | [@__object__]
53 | end
54 | result += args[0..1]
55 | result.compact.map(&:to_s).join('.').dasherize
56 | end
57 | end
58 |
59 | module CachedProxyExt
60 | def cached(key: nil, expires_in: 1.minute, recache: false)
61 | CachedProxy.new(
62 | self,
63 | key: key,
64 | expires_in: expires_in,
65 | recache: recache
66 | )
67 | end
68 | end
69 | end
70 |
71 | Object.send :include, RailsCachedMethod::CachedProxyExt
--------------------------------------------------------------------------------
/test/rails_cached_method_test.rb:
--------------------------------------------------------------------------------
1 | require "test_helper"
2 |
3 | class RailsCachedMethodTest < ActiveSupport::TestCase
4 | setup do
5 | Rails.cache.clear
6 | end
7 |
8 | test "it has a version number" do
9 | assert RailsCachedMethod::VERSION
10 | end
11 |
12 | test "it can cache simple things" do
13 | a = User.create(name: 'John', age: 100)
14 | b = User.create(name: 'Bob', age: 99)
15 |
16 | assert_equal 100, User.cached.maximum(:age)
17 | a.destroy
18 | assert_equal 100, User.cached.maximum(:age)
19 |
20 | assert_equal 99, User.cached(recache: true).maximum(:age)
21 | assert_equal 99, User.cached.maximum(:age)
22 |
23 | assert_equal 199, (User.cached.maximum(:age) + 100)
24 | end
25 |
26 | test "with relations" do
27 | a = User.create(name: 'John', age: 100)
28 | b = User.create(name: 'Bob', age: 99)
29 |
30 | ac = a.comments.create
31 | bc = b.comments.create
32 |
33 | assert a.cached.comments.count > 0
34 | assert a.cached.comments.any?
35 | assert_equal 1, a.cached.comments.count
36 | assert_equal 1, a.cached.comments.count
37 | assert_equal ac, a.cached.comments.first
38 |
39 | ac.destroy
40 | assert_equal ac, a.cached.comments.first
41 | a.reload
42 | assert_nil a.comments.first
43 | assert_nil a.cached(recache: true).comments.first
44 | end
45 |
46 | test 'in associations' do
47 | a = User.create(name: 'John', age: 100)
48 | b = User.create(name: 'Bob', age: 99)
49 |
50 | ac = a.comments.create
51 | bc1 = b.comments.create
52 | bc2 = b.comments.create
53 |
54 | assert_equal 2, User.cached.where(name: 'Bob').first.comments.count
55 | assert_equal 2, User.where(name: 'Bob').first.comments.count
56 |
57 | assert_equal b, User.cached.where(name: 'Bob').first.comments.first.user
58 | assert_equal b, User.where(name: 'Bob').first.comments.first.user
59 | end
60 |
61 | test 'in methods' do
62 | a = User.create(name: 'John', age: 100)
63 | b = User.create(name: 'Bob', age: 99)
64 |
65 | assert_equal 100, User.cached.find_maximum_age
66 | a.destroy
67 | assert_equal 100, User.cached.find_maximum_age
68 | assert_equal 99, User.cached(recache: true).find_maximum_age
69 |
70 | bc = b.comments.create
71 |
72 | c = User.cached.first.last_comment
73 | assert_equal c, bc
74 |
75 | e = Comment.cached.find_maximum_age
76 | assert_equal 'n/a', e
77 | end
78 | end
79 |
--------------------------------------------------------------------------------
/test/dummy/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | require "active_support/core_ext/integer/time"
2 |
3 | # The test environment is used exclusively to run your application's
4 | # test suite. You never need to work with it otherwise. Remember that
5 | # your test database is "scratch space" for the test suite and is wiped
6 | # and recreated between test runs. Don't rely on the data there!
7 |
8 | Rails.application.configure do
9 | # Settings specified here will take precedence over those in config/application.rb.
10 |
11 | config.cache_classes = true
12 |
13 | # Do not eager load code on boot. This avoids loading your whole application
14 | # just for the purpose of running a single test. If you are using a tool that
15 | # preloads Rails for running tests, you may have to set it to true.
16 | config.eager_load = false
17 |
18 | # Configure public file server for tests with Cache-Control for performance.
19 | config.public_file_server.enabled = true
20 | config.public_file_server.headers = {
21 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}"
22 | }
23 |
24 | # Show full error reports and disable caching.
25 | config.consider_all_requests_local = true
26 | config.action_controller.perform_caching = true
27 | config.cache_store = :memory_store
28 |
29 | # Raise exceptions instead of rendering exception templates.
30 | config.action_dispatch.show_exceptions = false
31 |
32 | # Disable request forgery protection in test environment.
33 | config.action_controller.allow_forgery_protection = false
34 |
35 | # Store uploaded files on the local file system in a temporary directory.
36 | config.active_storage.service = :test
37 |
38 | config.action_mailer.perform_caching = false
39 |
40 | # Tell Action Mailer not to deliver emails to the real world.
41 | # The :test delivery method accumulates sent emails in the
42 | # ActionMailer::Base.deliveries array.
43 | config.action_mailer.delivery_method = :test
44 |
45 | # Print deprecation notices to the stderr.
46 | config.active_support.deprecation = :stderr
47 |
48 | # Raise exceptions for disallowed deprecations.
49 | config.active_support.disallowed_deprecation = :raise
50 |
51 | # Tell Active Support which deprecation messages to disallow.
52 | config.active_support.disallowed_deprecation_warnings = []
53 |
54 | # Raises error for missing translations.
55 | # config.i18n.raise_on_missing_translations = true
56 |
57 | # Annotate rendered view with file names.
58 | # config.action_view.annotate_rendered_view_with_filenames = true
59 | end
60 |
--------------------------------------------------------------------------------
/test/dummy/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | require "active_support/core_ext/integer/time"
2 |
3 | Rails.application.configure do
4 | # Settings specified here will take precedence over those in config/application.rb.
5 |
6 | # In the development environment your application's code is reloaded any time
7 | # it changes. This slows down response time but is perfect for development
8 | # since you don't have to restart the web server when you make code changes.
9 | config.cache_classes = false
10 |
11 | # Do not eager load code on boot.
12 | config.eager_load = false
13 |
14 | # Show full error reports.
15 | config.consider_all_requests_local = true
16 |
17 | # Enable/disable caching. By default caching is disabled.
18 | # Run rails dev:cache to toggle caching.
19 | if Rails.root.join('tmp', 'caching-dev.txt').exist?
20 | config.action_controller.perform_caching = true
21 | config.action_controller.enable_fragment_cache_logging = true
22 |
23 | config.cache_store = :memory_store
24 | config.public_file_server.headers = {
25 | 'Cache-Control' => "public, max-age=#{2.days.to_i}"
26 | }
27 | else
28 | config.action_controller.perform_caching = true
29 |
30 | config.cache_store = :memory_store
31 | end
32 |
33 | # Store uploaded files on the local file system (see config/storage.yml for options).
34 | config.active_storage.service = :local
35 |
36 | # Don't care if the mailer can't send.
37 | config.action_mailer.raise_delivery_errors = false
38 |
39 | config.action_mailer.perform_caching = false
40 |
41 | # Print deprecation notices to the Rails logger.
42 | config.active_support.deprecation = :log
43 |
44 | # Raise exceptions for disallowed deprecations.
45 | config.active_support.disallowed_deprecation = :raise
46 |
47 | # Tell Active Support which deprecation messages to disallow.
48 | config.active_support.disallowed_deprecation_warnings = []
49 |
50 | # Raise an error on page load if there are pending migrations.
51 | config.active_record.migration_error = :page_load
52 |
53 | # Highlight code that triggered database queries in logs.
54 | config.active_record.verbose_query_logs = true
55 |
56 | # Debug mode disables concatenation and preprocessing of assets.
57 | # This option may cause significant delays in view rendering with a large
58 | # number of complex assets.
59 | config.assets.debug = true
60 |
61 | # Suppress logger output for asset requests.
62 | config.assets.quiet = true
63 |
64 | # Raises error for missing translations.
65 | # config.i18n.raise_on_missing_translations = true
66 |
67 | # Annotate rendered view with file names.
68 | # config.action_view.annotate_rendered_view_with_filenames = true
69 |
70 | # Use an evented file watcher to asynchronously detect changes in source code,
71 | # routes, locales, etc. This feature depends on the listen gem.
72 | # config.file_watcher = ActiveSupport::EventedFileUpdateChecker
73 |
74 | # Uncomment if you wish to allow Action Cable access from any origin.
75 | # config.action_cable.disable_request_forgery_protection = true
76 | end
77 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | PATH
2 | remote: .
3 | specs:
4 | rails_cached_method (0.1.1)
5 | rails
6 |
7 | GEM
8 | remote: https://rubygems.org/
9 | specs:
10 | actioncable (6.1.3.2)
11 | actionpack (= 6.1.3.2)
12 | activesupport (= 6.1.3.2)
13 | nio4r (~> 2.0)
14 | websocket-driver (>= 0.6.1)
15 | actionmailbox (6.1.3.2)
16 | actionpack (= 6.1.3.2)
17 | activejob (= 6.1.3.2)
18 | activerecord (= 6.1.3.2)
19 | activestorage (= 6.1.3.2)
20 | activesupport (= 6.1.3.2)
21 | mail (>= 2.7.1)
22 | actionmailer (6.1.3.2)
23 | actionpack (= 6.1.3.2)
24 | actionview (= 6.1.3.2)
25 | activejob (= 6.1.3.2)
26 | activesupport (= 6.1.3.2)
27 | mail (~> 2.5, >= 2.5.4)
28 | rails-dom-testing (~> 2.0)
29 | actionpack (6.1.3.2)
30 | actionview (= 6.1.3.2)
31 | activesupport (= 6.1.3.2)
32 | rack (~> 2.0, >= 2.0.9)
33 | rack-test (>= 0.6.3)
34 | rails-dom-testing (~> 2.0)
35 | rails-html-sanitizer (~> 1.0, >= 1.2.0)
36 | actiontext (6.1.3.2)
37 | actionpack (= 6.1.3.2)
38 | activerecord (= 6.1.3.2)
39 | activestorage (= 6.1.3.2)
40 | activesupport (= 6.1.3.2)
41 | nokogiri (>= 1.8.5)
42 | actionview (6.1.3.2)
43 | activesupport (= 6.1.3.2)
44 | builder (~> 3.1)
45 | erubi (~> 1.4)
46 | rails-dom-testing (~> 2.0)
47 | rails-html-sanitizer (~> 1.1, >= 1.2.0)
48 | activejob (6.1.3.2)
49 | activesupport (= 6.1.3.2)
50 | globalid (>= 0.3.6)
51 | activemodel (6.1.3.2)
52 | activesupport (= 6.1.3.2)
53 | activerecord (6.1.3.2)
54 | activemodel (= 6.1.3.2)
55 | activesupport (= 6.1.3.2)
56 | activestorage (6.1.3.2)
57 | actionpack (= 6.1.3.2)
58 | activejob (= 6.1.3.2)
59 | activerecord (= 6.1.3.2)
60 | activesupport (= 6.1.3.2)
61 | marcel (~> 1.0.0)
62 | mini_mime (~> 1.0.2)
63 | activesupport (6.1.3.2)
64 | concurrent-ruby (~> 1.0, >= 1.0.2)
65 | i18n (>= 1.6, < 2)
66 | minitest (>= 5.1)
67 | tzinfo (~> 2.0)
68 | zeitwerk (~> 2.3)
69 | builder (3.2.4)
70 | coderay (1.1.3)
71 | concurrent-ruby (1.1.9)
72 | crass (1.0.6)
73 | erubi (1.10.0)
74 | globalid (0.4.2)
75 | activesupport (>= 4.2.0)
76 | i18n (1.8.10)
77 | concurrent-ruby (~> 1.0)
78 | loofah (2.10.0)
79 | crass (~> 1.0.2)
80 | nokogiri (>= 1.5.9)
81 | mail (2.7.1)
82 | mini_mime (>= 0.1.1)
83 | marcel (1.0.1)
84 | method_source (1.0.0)
85 | mini_mime (1.0.3)
86 | minitest (5.14.4)
87 | nio4r (2.5.7)
88 | nokogiri (1.11.7-x86_64-linux)
89 | racc (~> 1.4)
90 | pry (0.14.1)
91 | coderay (~> 1.1)
92 | method_source (~> 1.0)
93 | racc (1.5.2)
94 | rack (2.2.3)
95 | rack-test (1.1.0)
96 | rack (>= 1.0, < 3)
97 | rails (6.1.3.2)
98 | actioncable (= 6.1.3.2)
99 | actionmailbox (= 6.1.3.2)
100 | actionmailer (= 6.1.3.2)
101 | actionpack (= 6.1.3.2)
102 | actiontext (= 6.1.3.2)
103 | actionview (= 6.1.3.2)
104 | activejob (= 6.1.3.2)
105 | activemodel (= 6.1.3.2)
106 | activerecord (= 6.1.3.2)
107 | activestorage (= 6.1.3.2)
108 | activesupport (= 6.1.3.2)
109 | bundler (>= 1.15.0)
110 | railties (= 6.1.3.2)
111 | sprockets-rails (>= 2.0.0)
112 | rails-dom-testing (2.0.3)
113 | activesupport (>= 4.2.0)
114 | nokogiri (>= 1.6)
115 | rails-html-sanitizer (1.3.0)
116 | loofah (~> 2.3)
117 | railties (6.1.3.2)
118 | actionpack (= 6.1.3.2)
119 | activesupport (= 6.1.3.2)
120 | method_source
121 | rake (>= 0.8.7)
122 | thor (~> 1.0)
123 | rake (13.0.3)
124 | sprockets (4.0.2)
125 | concurrent-ruby (~> 1.0)
126 | rack (> 1, < 3)
127 | sprockets-rails (3.2.2)
128 | actionpack (>= 4.0)
129 | activesupport (>= 4.0)
130 | sprockets (>= 3.0.0)
131 | sqlite3 (1.4.2)
132 | thor (1.1.0)
133 | tzinfo (2.0.4)
134 | concurrent-ruby (~> 1.0)
135 | websocket-driver (0.7.5)
136 | websocket-extensions (>= 0.1.0)
137 | websocket-extensions (0.1.5)
138 | zeitwerk (2.4.2)
139 |
140 | PLATFORMS
141 | ruby
142 |
143 | DEPENDENCIES
144 | pry
145 | rails_cached_method!
146 | sqlite3
147 |
148 | BUNDLED WITH
149 | 2.1.3
150 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Rails Cached Method
2 |
3 | [](https://www.railsjazz.com)
4 | [](https://www.patreon.com/igorkasyanchuk)
5 |
6 | [](https://buymeacoffee.com/igorkasyanchuk)
7 |
8 | Simple way to cache results of methods. Using `Rails.cache` inside with default expiration time of 1 minute.
9 |
10 | 
11 |
12 | ## Usage
13 |
14 | To get a value and cache it just write a code like:
15 |
16 | ```ruby
17 | User.cached.admins # get list of admins and automatically put them in cache with 1 minute TTL
18 | post.cached.comments.last # get last comment from the post and cache it
19 | User.cached.where(role: :moderator).count # cache moderators count
20 | Project.cached.first.some_heavey_method # cache result of some_heavey_method for first Project (if first is Project.first)
21 | ```
22 |
23 | So basically just call method `cached` on any object. It will wrap and cache **every** result from the next method call. So every result from method chain is cached.
24 |
25 | For example:
26 |
27 | ```ruby
28 | post.cached.comments.first # A
29 | post.cached.comments.last # B
30 | ```
31 |
32 | Here `post.cached.comments` will return same collection.
33 |
34 | You don't need to specify a key, because it's dynamically set based on object, arguments, etc.
35 |
36 | Options:
37 |
38 | ```ruby
39 | cached(key: nil, expires_in: 1.minute, recache: false)
40 | ```
41 |
42 | key - you can set your key.
43 | expires_in - TTL of cached object.
44 | recache - should be key deleted and cached again.
45 |
46 | ## Tips & Tricks
47 |
48 | 1) use `if page.present?` to check if value is really present. Because every value is wrapped in a class if statement can work incorrectly
49 | ```ruby
50 | page = Page.cached.find_by(identifier: identifier)
51 | return page if page # change to return page if page.present?
52 | page = Page.new(identifier: identifier, title: identifier)
53 | page.save(validate: false)
54 | page
55 | ```
56 |
57 | 2) Rails.cache.clear in specs before(:suite) or concrete spec
58 |
59 |
60 | ## How it works
61 |
62 | After you call `.cached` it will generate a cache key and store value in Rails.cache. Value is class which is wrapps original value and allow you to call methods on the value using `method_missing`. Every result is cached again and again. So on every method call in methods chain every result will be stored in Rails.cache.
63 |
64 | To get original value you can call `.__value__`.
65 |
66 | Some pieces of code to show you how it works:
67 |
68 | ```ruby
69 | def cached(key: nil, expires_in: 1.minute, recache: false)
70 | CachedProxy.new(
71 | self,
72 | key: key,
73 | expires_in: expires_in,
74 | recache: recache
75 | )
76 | end
77 | # ---------------------------------------------------------------
78 | class CachedProxy
79 |
80 | Object.methods.each do |e|
81 | delegate e, to: :@__object__
82 | end
83 |
84 | def method_missing(*args)
85 | key = ___compose_key__(args)
86 | if @__recache__
87 | Rails.cache.delete(key)
88 | end
89 | Rails.cache.fetch(key, expires_in: @__expires_in__) do
90 | CachedProxy.new(
91 | @__object__.send(*args),
92 | expires_in: @__expires_in__,
93 | recache: @__recache__,
94 | parent_key: key,
95 | )
96 | end
97 | end
98 | private
99 | def ___compose_key__(args)
100 | result = [@__parent_key__, @__key__]
101 | result += if @__object__.respond_to?(:to_global_id)
102 | [@__object__.to_global_id]
103 | elsif @__object__.is_a?(ActiveRecord::Relation)
104 | [@__object__.class]
105 | else
106 | [@__object__]
107 | end
108 | result += args[0..1]
109 | result.compact.map(&:to_s).join('.').dasherize
110 | end
111 | ```
112 |
113 | ## Installation
114 | Add this line to your application's Gemfile:
115 |
116 | ```ruby
117 | gem 'rails_cached_method'
118 | ```
119 |
120 | And then execute:
121 | ```bash
122 | $ bundle
123 | ```
124 |
125 | Or install it yourself as:
126 | ```bash
127 | $ gem install rails_cached_method
128 | ```
129 |
130 | ## TODO
131 |
132 | - think if rails dependency could be replaced with something more lightweight
133 |
134 | ## Contributing
135 | Contribution directions go here.
136 |
137 | ## License
138 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
139 |
140 | [
](https://www.railsjazz.com/?utm_source=github&utm_medium=bottom&utm_campaign=rails_cached_method)
142 |
143 | [](https://buymeacoffee.com/igorkasyanchuk)
144 |
--------------------------------------------------------------------------------
/test/dummy/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | require "active_support/core_ext/integer/time"
2 |
3 | Rails.application.configure do
4 | # Settings specified here will take precedence over those in config/application.rb.
5 |
6 | # Code is not reloaded between requests.
7 | config.cache_classes = true
8 |
9 | # Eager load code on boot. This eager loads most of Rails and
10 | # your application in memory, allowing both threaded web servers
11 | # and those relying on copy on write to perform better.
12 | # Rake tasks automatically ignore this option for performance.
13 | config.eager_load = true
14 |
15 | # Full error reports are disabled and caching is turned on.
16 | config.consider_all_requests_local = false
17 | config.action_controller.perform_caching = true
18 |
19 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
20 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
21 | # config.require_master_key = true
22 |
23 | # Disable serving static files from the `/public` folder by default since
24 | # Apache or NGINX already handles this.
25 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
26 |
27 | # Compress CSS using a preprocessor.
28 | # config.assets.css_compressor = :sass
29 |
30 | # Do not fallback to assets pipeline if a precompiled asset is missed.
31 | config.assets.compile = false
32 |
33 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
34 | # config.asset_host = 'http://assets.example.com'
35 |
36 | # Specifies the header that your server uses for sending files.
37 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
38 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
39 |
40 | # Store uploaded files on the local file system (see config/storage.yml for options).
41 | config.active_storage.service = :local
42 |
43 | # Mount Action Cable outside main process or domain.
44 | # config.action_cable.mount_path = nil
45 | # config.action_cable.url = 'wss://example.com/cable'
46 | # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
47 |
48 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
49 | # config.force_ssl = true
50 |
51 | # Include generic and useful information about system operation, but avoid logging too much
52 | # information to avoid inadvertent exposure of personally identifiable information (PII).
53 | config.log_level = :info
54 |
55 | # Prepend all log lines with the following tags.
56 | config.log_tags = [ :request_id ]
57 |
58 | # Use a different cache store in production.
59 | # config.cache_store = :mem_cache_store
60 |
61 | # Use a real queuing backend for Active Job (and separate queues per environment).
62 | # config.active_job.queue_adapter = :resque
63 | # config.active_job.queue_name_prefix = "dummy_production"
64 |
65 | config.action_mailer.perform_caching = false
66 |
67 | # Ignore bad email addresses and do not raise email delivery errors.
68 | # Set this to true and configure the email server for immediate delivery to raise delivery errors.
69 | # config.action_mailer.raise_delivery_errors = false
70 |
71 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
72 | # the I18n.default_locale when a translation cannot be found).
73 | config.i18n.fallbacks = true
74 |
75 | # Send deprecation notices to registered listeners.
76 | config.active_support.deprecation = :notify
77 |
78 | # Log disallowed deprecations.
79 | config.active_support.disallowed_deprecation = :log
80 |
81 | # Tell Active Support which deprecation messages to disallow.
82 | config.active_support.disallowed_deprecation_warnings = []
83 |
84 | # Use default logging formatter so that PID and timestamp are not suppressed.
85 | config.log_formatter = ::Logger::Formatter.new
86 |
87 | # Use a different logger for distributed setups.
88 | # require "syslog/logger"
89 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
90 |
91 | if ENV["RAILS_LOG_TO_STDOUT"].present?
92 | logger = ActiveSupport::Logger.new(STDOUT)
93 | logger.formatter = config.log_formatter
94 | config.logger = ActiveSupport::TaggedLogging.new(logger)
95 | end
96 |
97 | # Do not dump schema after migrations.
98 | config.active_record.dump_schema_after_migration = false
99 |
100 | # Inserts middleware to perform automatic connection switching.
101 | # The `database_selector` hash is used to pass options to the DatabaseSelector
102 | # middleware. The `delay` is used to determine how long to wait after a write
103 | # to send a subsequent read to the primary.
104 | #
105 | # The `database_resolver` class is used by the middleware to determine which
106 | # database is appropriate to use based on the time delay.
107 | #
108 | # The `database_resolver_context` class is used by the middleware to set
109 | # timestamps for the last write to the primary. The resolver uses the context
110 | # class timestamps to determine how long to wait before reading from the
111 | # replica.
112 | #
113 | # By default Rails will store a last write timestamp in the session. The
114 | # DatabaseSelector middleware is designed as such you can define your own
115 | # strategy for connection switching and pass that into the middleware through
116 | # these configuration options.
117 | # config.active_record.database_selector = { delay: 2.seconds }
118 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
119 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
120 | end
121 |
--------------------------------------------------------------------------------