Skip to content

willbryant/constant_table_saver

Repository files navigation

ConstantTableSaver

Loads all records from the table on first use, and thereafter returns the cached (and frozen) records for all find calls.

Optionally, creates class-level methods you can use to grab the records, named after the name field you specify.

Compatibility

Currently tested against Rails 6.1.0.rc1, 6.0.3.4, 5.2.4.4, 5.1.7, and 5.0.7.2, with older gem versions compatible with earlier Rails versions.

Example

Problem: the following code would load each txn_type individually:

    Txn.all.each {|txn| .. do something with txn.txn_type ..}

You can improve this a bit with standard Rails:

    Txn.preload(:txn_type).all.each {|txn| .. do something with txn.txn_type ..}

This would load the txn_types in one go after the txns query, but would still need a query every time you load txns.

But if you use constant_table_saver, without needing to use a preload:

    class TxnType
      constant_table
    end

    Txn.all.each {|txn| .. do something with txn.txn_type ..}

It will no longer requires individual txn_type loads, just every time you start the server (or every request, in development mode). Most other basic queries are also cached:

    TxnType.all.to_a

But other scopes with options still result in actual queries:

    TxnType.where("name LIKE '%foo%'").to_a
    TxnType.lock.find(2)

You can also use:

    class TxnType
      constant_table :name => :label
    end

Which if you have:

    TxnType.create!(:label => "Customer Purchase")
    TxnType.create!(:label => "Refund")

Means you will also have methods returning those records:

    TxnType.customer_purchase
    TxnType.refund

Optionally, you can specify a :name_prefix and/or :name_suffix.

Thanks

  • Marc Shaw (@marcshaw)

Copyright (c) 2010-2020 Will Bryant, Sekuda Ltd, released under the MIT license

About

Caches loads from entirely-constant tables

Resources

License

Stars

Watchers

Forks

Packages

No packages published