# Copyright (c) 2006 Danger Canty http://6brand.com # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Many thanks to Rick Olson (http://techno-weenie.net) # This plugin (like countless others) was only written after a careful # examination of his productions. module ActiveRecord #:nodoc: module Acts #:nodoc: module Zipcoded def self.included(base) # :nodoc: base.extend ClassMethods end module ClassMethods def acts_as_zipcoded(options = {}, &extension) # don't allow multiple calls return if self.included_modules.include?(ActiveRecord::Acts::Zipcoded::ActMethods) include ActiveRecord::Acts::Zipcoded::ActMethods class_eval do belongs_to :acts_as_zipcoded_model, :class_name => 'Zip', :foreign_key => :zip_id end # create the Zip model const_set('Zip', Class.new(ActiveRecord::Base)).class_eval do def before_save; false; end end end end module ActMethods def zipcode self.zip_id end def zipcode=(code) self.acts_as_zipcoded_model = Zip.find(code) rescue nil end def city acts_as_zipcoded_model ? acts_as_zipcoded_model.city : nil end def state acts_as_zipcoded_model ? acts_as_zipcoded_model.state : nil end end end end end ActiveRecord::Base.send :include, ActiveRecord::Acts::Zipcoded