Skip to content

Instantly share code, notes, and snippets.

@ritikesh
ritikesh / creator.rb
Last active October 13, 2020 20:36
Creator Pattern
module Creator
extend ActiveSupport::Concern
included do
before_validation -> {
self.creator_id = User.current.id if User.current
}, on: :create
belongs_to :creator, class_name: 'User', foreign_key: :creator_id
end
@ritikesh
ritikesh / acts_as_current.rb
Last active November 27, 2018 18:30
Current pattern
module ActsAsCurrent
extend ActiveSupport::Concern
included do
self._current_human_name = self.name.underscore.to_sym
end
def make_current
Thread.current[self.class._current_human_name] = self
end
@ritikesh
ritikesh / belongs_to_tenant.rb
Last active November 27, 2018 18:01
Model Concern for a multi-tenant rails app
module BelongsToTenant
extend ActiveSupport::Concern
included do
belongs_to :tenant
default_scope {
Tenant.current ? where(tenant_id: Tenant.current.id) : where(nil)
}
end
@ritikesh
ritikesh / deep_freeze.rb
Created July 7, 2017 09:03
Simple deep freeze for Ruby Enumerables
module Enumerable
def deep_freeze
obj = self
obj.each do |iterator|
case iterator
when Enumerable
iterator.deep_freeze
when Symbol, Fixnum, NilClass
iterator
else
@ritikesh
ritikesh / memoize.rb
Last active November 30, 2018 02:50
Ruby/Rails Memoization pattern for dynamic methods created using metaprogramming
# memoize db/memcache results in instance variable dynamically
def memoize_results(key)
return instance_variable_get(key) if instance_variable_defined?(key)
instance_variable_set key, yield
end
# usage
MY_CONSTANT = [:active, :inactive]
MY_CONSTANT.each { |key|
define_method("#{key}_users") do
@ritikesh
ritikesh / rails3_activerecord_monkey_patch.rb
Last active August 10, 2016 16:20
Rails 3 - Extra join conditions for ActiveRecord "through" joins - eg.) table1.account_id = table2.account_id
module AccountJoinCondition
def join_with_account(table, constraint)
s_r = reflection.source_reflection
# source reflection can be polymorphic
s_r = reflection if s_r && s_r.options[:polymorphic]
t_r = reflection.through_reflection
if s_r && t_r && has_account?(s_r) && has_account?(t_r)
sr_account_column = account_col(s_r)
tr_account_column = account_col(t_r)
constraint = constraint.and(sr_account_column.eq(tr_account_column)) if direct_through_join?(sr_account_column, tr_account_column, constraint)