Skip to content

Instantly share code, notes, and snippets.

@LRDesign
Created May 5, 2010 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LRDesign/391609 to your computer and use it in GitHub Desktop.
Save LRDesign/391609 to your computer and use it in GitHub Desktop.
# Gives the ability to cascade upward for an attribute in a nested_set
# So, for example, if a project does not have a client specified, it will
# inherit the client of its parent, or further ancestor.
module Cascade
def self.included(klass)
klass.extend(ClassMethods)
end
module ClassMethods
def cascades(*args)
args.each do |attrib|
if column_names.any?{|n| n==attrib.to_s}
p "defining attribute version for #{attrib}"
class_eval <<-EOM, __FILE__, __LINE__
def #{attrib}
p "foo"
if read_attribute(#{attrib}).blank?
p "bar1"
ancestors.reverse.find{|a| !a.read_attribute(#{attrib}).blank? }.read_attribute(#{attrib})
else
p "bar2"
read_attribute(#{attrib})
end
end
EOM
else
p "defining method version for #{attrib}"
class_eval <<-EOM2, __FILE__, __LINE__
def #{attrib}_with_cascade
if #{attrib}_without_cascade.blank?
ancestors.reverse.find{|a| !a.#{attrib}_without_cascade.blank? }.#{attrib}_without_cascade
else
#{attrib}_without_cascade
end
end
EOM2
alias_method_chain attrib, :cascade
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment