module ActiveRecordDefineNils::Model::ClassMethods
Public Instance Methods
belongs_to(*args)
click to toggle source
Calls superclass method
# File lib/activerecord-define_nils/model.rb, line 30 def belongs_to(*args) super(*args) return unless self.nil_definitions # after belongs_to is finished, we wrap it self.nil_definitions.keys.each do |attr_sym| self.reflections.collect {|association_name, reflection| if reflection.macro == :belongs_to && reflection.foreign_key.to_sym == attr_sym class_eval "def #{association_name}; return nil if __send__(#{attr_sym.inspect}).nil?; super(); end" end } end end
define_nils(options)
click to toggle source
# File lib/activerecord-define_nils/model.rb, line 12 def define_nils(options) raise ArgumentError.new("define_nils takes a hash, but got #{options.inspect}") unless options.is_a?(Hash) if options.has_key?(:as) && options.has_key?(:for) self.nil_saved_as ||= {} self.nil_definitions ||= {} as_vals = Array.wrap(options[:as]) raise ArgumentError.new("define_nils must supply at least one value for :as, but got #{options.inspect}") if as_vals.size == 0 Array.wrap(options[:for]).each do |attr_name| attr_sym = attr_name.to_sym self.nil_saved_as[attr_sym] = options.key?(:saving_as) ? options[:saving_as] : as_vals[0] self.nil_definitions[attr_sym] = as_vals class_eval "def #{attr_name}; value = super(); self.nil_definitions && self.nil_definitions[#{attr_sym.inspect}] && self.nil_definitions[#{attr_sym.inspect}].include?(value) ? nil : value; end" end else raise ArgumentError.new("define_nils takes a hash with :as and :for keys, but got #{options.inspect}") end end