Skip to content

Instantly share code, notes, and snippets.

View zhandao's full-sized avatar
🎯
(๑ ̀ㅅ ́๑)

阙溪台 zhandao

🎯
(๑ ̀ㅅ ́๑)
View GitHub Profile
@zhandao
zhandao / having or missing assoc.rb
Created November 10, 2023 06:18
[Ruby on Rails] having or missing associations with filter
module HavingAssoc
extend ActiveSupport::Concern
class_methods do
# @example
# Child.missing_assoc(:lessons)
# Child.missing_assoc(:lessons).size # => children's count
# Child.missing_assoc(:lessons, filter: Lesson.finished) # => [children]
def missing_assoc(assoc_name, filter: nil)
if filter.nil?
@zhandao
zhandao / ar jsonb & array query.md
Last active November 10, 2023 06:51
[Ruby on Rails] ActiveRecord Postgresql Jsonb & Array Query

Jsonb Query Scopes

Based on [https://github.com/DmitryTsepelev/store_model]

module JsonbQuery
  extend ActiveSupport::Concern

  included do
    # where_jsonb(:info, { name: "John", age: 18..28, date: "< 2020-01-01" })
    scope :where_jsonb, -> (column_name, attributes) do
@zhandao
zhandao / pryrc.md
Last active November 10, 2023 05:44
[Ruby] my Pry settings and useful commands (.pryrc)

Find histories

# separate history file into current project
Pry.config.history_file = ".pry_history"

# @usage
#   hist User.first
#   hist User.first 3
#   hist User.first 3 5
@zhandao
zhandao / memory_take.md
Last active November 10, 2023 07:05
[Ruby on Rails] Let ActiveRecord take record instance directly from memory (cached)

inspired by [https://sourcediving.com/this-rails-cache-is-not-your-friend-512871c138aa]

Let ActiveRecord take record instance directly from memory (cached), instead of instantiate from result set, for reducing memory allocation times and time.

It is very simple implementation of Identity Map.

It is suitable for reading is much more frequent than updating, like hot posts (preferably non editable).

@zhandao
zhandao / main.md
Last active November 10, 2023 05:37
[Ruby on Rails] Define method inside ActiveRecord result instance

des to be written.

class User < ApplicationRecord
  def self.select_tag = all.select { _1.tags.present? }

  relation_delegate_class(ActiveRecord::Relation).class_eval do
    def select_age = select { _1.age in ..18 }
    def find_loaded_by(**) = find { my_match?(_1, **) }
 end