Skip to content

Instantly share code, notes, and snippets.

View sbfaulkner's full-sized avatar

S. Brent Faulkner sbfaulkner

  • Shopify
  • Caledon, ON CANADA
View GitHub Profile
@sbfaulkner
sbfaulkner / to_yaml.rb
Created February 5, 2009 07:03
an alternate (more aggressive) approach to making to_yaml work
module ActiveRecord
class Base
def to_yaml_with_association_pruning(opts = {})
# detect and remove any cached associations
self.class.reflect_on_all_associations.each do |a|
ivar = "@#{a.name}"
remove_instance_variable(ivar) if instance_variable_defined?(ivar)
end
to_yaml_without_association_pruning(opts)
end
@sbfaulkner
sbfaulkner / to_yaml.rb
Created February 5, 2009 06:27
fix to_yaml when dumping ActiveRecord instances with nil association_proxies
module ActiveRecord
class Base
def to_yaml_with_nil_handling(opts = {})
# detect and remove any belongs_to association proxies
self.class.reflect_on_all_associations.find_all { |a| a.macro == :belongs_to }.each do |a|
ivar = "@#{a.name}"
remove_instance_variable(ivar) if instance_variable_defined?(ivar) && instance_variable_get(ivar).class.nil?
end
to_yaml_without_nil_handling(opts)
end