Sha256: 5449b2b6433b50457e9910eef402bdb0c73de0026657cfd257d9a94ecac2c75a
Contents?: true
Size: 1.43 KB
Versions: 1
Compression:
Stored size: 1.43 KB
Contents
require "cached_belongs_to/version" require 'active_record' module CachedBelongsTo module ClassMethods def cached_belongs_to(*args) caches = Array(args[1].delete(:caches)) klass = args[0] belongs_to(*args) children_hook_name = "cached_belongs_to_#{name.underscore}_after_save".to_sym create_cached_belongs_to_child_hooks(caches, klass, children_hook_name) create_cached_belongs_to_parent_hooks(caches, klass, children_hook_name) end def create_cached_belongs_to_child_hooks(*args, caches, klass, children_hook_name) define_method children_hook_name do caches.each do |attr| send("#{klass}_#{attr}=", send(klass).send(attr)) if send(klass) end end before_save children_hook_name end def create_cached_belongs_to_parent_hooks(caches, parent_class_name, children_hook_name) method_name = "cached_belongs_to_#{parent_class_name}_after_save".to_sym has_many_association = self.name.underscore.pluralize.to_sym parent_class = parent_class_name.to_s.camelize.constantize parent_class.send(:define_method, method_name) do send(has_many_association).reload.each do |child| caches.each do |attr| child.send(children_hook_name) child.save end end end parent_class.send(:after_save, method_name) end end end ActiveRecord::Base.extend(CachedBelongsTo::ClassMethods)
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
cached_belongs_to-0.0.1 | lib/cached_belongs_to.rb |