• Stars
    star
    11
  • Rank 1,694,829 (Top 34 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 3 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple way to cache results of methods.

Rails Cached Method

RailsJazz https://www.patreon.com/igorkasyanchuk

Simple way to cache results of methods. Using Rails.cache inside with default expiration time of 1 minute.

Demo

Usage

To get a value and cache it just write a code like:

User.cached.admins # get list of admins and automatically put them in cache with 1 minute TTL
post.cached.comments.last # get last comment from the post and cache it
User.cached.where(role: :moderator).count # cache moderators count
Project.cached.first.some_heavey_method # cache result of some_heavey_method for first Project (if first is Project.first)

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.

For example:

post.cached.comments.first # A
post.cached.comments.last  # B

Here post.cached.comments will return same collection.

You don't need to specify a key, because it's dynamically set based on object, arguments, etc.

Options:

cached(key: nil, expires_in: 1.minute, recache: false)

key - you can set your key. expires_in - TTL of cached object. recache - should be key deleted and cached again.

Tips & Tricks

  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
    page = Page.cached.find_by(identifier: identifier)
    return page if page # change to return page if page.present?
    page = Page.new(identifier: identifier, title: identifier)
    page.save(validate: false)
    page
  1. Rails.cache.clear in specs before(:suite) or concrete spec

How it works

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.

To get original value you can call .__value__.

Some pieces of code to show you how it works:

    def cached(key: nil, expires_in: 1.minute, recache: false)
      CachedProxy.new(
        self,
        key: key,
        expires_in: expires_in,
        recache: recache
      )
    end
# ---------------------------------------------------------------
    class CachedProxy

    Object.methods.each do |e|
      delegate e, to: :@__object__
    end
    
    def method_missing(*args)
      key = ___compose_key__(args)
      if @__recache__
        Rails.cache.delete(key)
      end
      Rails.cache.fetch(key, expires_in: @__expires_in__) do
        CachedProxy.new(
          @__object__.send(*args),
          expires_in: @__expires_in__,
          recache: @__recache__,
          parent_key: key,
        )
      end
    end    
    private
    def ___compose_key__(args)
      result = [@__parent_key__, @__key__]
      result += if @__object__.respond_to?(:to_global_id)
        [@__object__.to_global_id]
      elsif @__object__.is_a?(ActiveRecord::Relation)
        [@__object__.class]
      else
        [@__object__]
      end
      result += args[0..1]
      result.compact.map(&:to_s).join('.').dasherize
    end

Installation

Add this line to your application's Gemfile:

gem 'rails_cached_method'

And then execute:

$ bundle

Or install it yourself as:

$ gem install rails_cached_method

TODO

  • think if rails dependency could be replaced with something more lightweight

Contributing

Contribution directions go here.

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

rails_db

Rails Database Viewer and SQL Query Runner
JavaScript
1,447
star
2

active_storage_validations

Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, max: 3 }, aspect_ratio: :landscape, dimension: { width: { in: 800..1600 }
Ruby
959
star
3

rails_performance

Monitor performance of you Rails applications (self-hosted and free)
Ruby
793
star
4

any_login

Easy way to login as any user in system
Ruby
376
star
5

log_analyzer

Rails logs analyzer (see how fast your views are rendering)
Ruby
349
star
6

rails_pdf

A reliable way to generate PDF of any complexity in Ruby on Rails apps
HTML
175
star
7

fake_api

The fastest way to prototype API in your Rails application
Ruby
142
star
8

execution_time

How fast is your code? See it directly in Rails console.
Ruby
111
star
9

benchmark_methods

Benchmark and measure execution time your Ruby methods without an additional code changes
Ruby
89
star
10

new_google_recaptcha

reCAPTCHA v3 Ruby on Rails gem
Ruby
82
star
11

transactify

Wrap your methods in DB Transactions
Ruby
55
star
12

sql_view

Rails SQL Views made easy ;)
Ruby
49
star
13

sweet_staging

Access your Rails console, see logs, execute rake commands directly from the browser. Great addition to your Staging ENV.
JavaScript
46
star
14

execute_sql

Execute SQL inside Rails console, or app itself
Ruby
41
star
15

cache_with_locale

Easy wait to do view caching with automatically added "locale" value to the cached key.
Ruby
37
star
16

avatarro

Generate google-style avatars in your application
Ruby
37
star
17

awesome_back_url

Redirect the user to the proper "back" page
Ruby
33
star
18

records_count

See in development logs how many records your queries returns. It can help with solving performance issues.
Ruby
31
star
19

new_ckeditor

Ruby on Rails + CKEditor 5
Ruby
31
star
20

amazon_static_site

Static website using https with your own domain name using Amazon S3 and Cloudflare for FREE
Ruby
29
star
21

omg_image

Generate PNG previews for HTML snippets (html/css/js). Any complexity.
Ruby
28
star
22

wrapped_print

Easy print debug information to your console in Ruby/Rails app.
Ruby
23
star
23

calculate_in_group

Group Active Record by ranges or set of values with a single SQL query.
Ruby
22
star
24

embed_view

Embed ERB files inside another ERB files for faster performance (5-20% BOOST!!!)
HTML
21
star
25

rails_time_travel

HTML
19
star
26

sabotage

Coding & debugging must be fun. Make life a bit harder for your colleagues :)
Ruby
18
star
27

mechanical

All models in a single table, new attributes without migrations. Works like regular AR model
Ruby
17
star
28

secrett11tto

Simple way to protect your content from copy-pasting
Ruby
15
star
29

rails_live

Ruby
15
star
30

mini-guard

Ruby
14
star
31

railsjazz.com

Rails Jazz (personal web site)
JavaScript
14
star
32

sidekiq_log_analyzer

SidekiqLogAnalyser gem allows to see summary of your sidekiq workers (based on log file).
Ruby
13
star
33

hasharay_ext

Painless work with complex Ruby hashes/arrays.
Ruby
13
star
34

active_storage_silent_logs

The idea of this gem is to hide as much as possible Active Storage logs from console so you can see only important information and requests
Ruby
13
star
35

with_record

Returns relations/association for soft deleted records in DB
Ruby
10
star
36

rrr

Run recent rspec files only (the only recently modified).
Ruby
9
star
37

font_awesome_file_icons

Ruby
4
star
38

unwhere

Ruby
4
star
39

travel_and_talk

JavaScript
3
star
40

lazy_mobile_tester

Rails Lazy Mobile Tester
Ruby
3
star
41

serpjazz

SERP keywords tracking
JavaScript
3
star
42

jeanappv2

JavaScript
2
star
43

slim_erb_backport

Slim 4+ and ERB friends again :)
Ruby
2
star
44

mega-simple-authorization

mega simple authorization plugin for RoR
Ruby
2
star
45

tv

eb5 tv
JavaScript
2
star
46

spring_rspec_commands_addon

rails+spring+rspec = friends :)
Ruby
2
star
47

layouts_from_db_sample

Allow store layouts to DB (Sample)
2
star
48

CheaperDrinker

CheaperDrinker web site
JavaScript
2
star
49

tell_my_env

Ruby
2
star
50

any_login_test

AnyLogin gem test application
Ruby
2
star
51

VerySimple

1
star
52

ShareT

online translations
JavaScript
1
star
53

test-ec2

test-ec2
1
star
54

sa1

1
star
55

better_tempfile

Ruby
1
star
56

ar_enumerations_test_application

ActiveRecord enumeration field type - test application
Ruby
1
star
57

tophouse.com.ua

JavaScript
1
star
58

capistranotest

1
star
59

zip_and_phone

Zips & Phones
Ruby
1
star
60

portfolio

1
star
61

tdemo

tdemo
Ruby
1
star
62

cisarska_and_frankivska

Cisarska & Frankivska
JavaScript
1
star
63

seminars

JavaScript
1
star
64

deprecations_collector

Save all Rails deprecation in log file for future investigation
Ruby
1
star
65

just_for_fun

Do you want to call 42.to_user, [42, 43, 44].to_users? Try this gem :)
Ruby
1
star
66

rails_logs

Ruby
1
star