Skip to content

Instantly share code, notes, and snippets.

@jamescook
Created May 24, 2011 14:31
Show Gist options
  • Save jamescook/988811 to your computer and use it in GitHub Desktop.
Save jamescook/988811 to your computer and use it in GitHub Desktop.
# Include in classes that have an Address
# Adds shortcut getter/setter methods for line1, line2, city, state, zip.
module AddressDelegation
extend ActiveSupport::Concern
included do
include InstanceMethods
def assign_attributes_with_delegation attributes, options
setup_address
delegate_address_attributes
assign_attributes_without_delegation attributes, options
end
alias_method_chain :assign_attributes, :delegation
after_initialize :setup_address
after_initialize :delegate_address_attributes
end
module InstanceMethods
protected
def _address_reflection
@_address_reflection ||= reflections.keys.detect{|k| k.to_s =~ /address/ }
end
def _address
@_address
end
def delegate_address_attributes
[ "state", "city", "zip", "line1", "line2" ].each do |col|
self.class.delegate :"#{col}", :"#{col}=", :to => :_address
end
end
def setup_address
instance = nil
if _address_reflection
instance = (new_record? && send(_address_reflection).nil?) ? send(:"build_#{_address_reflection}") : send(_address_reflection)
puts instance
end
self.instance_variable_set("@_address", instance)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment