Skip to content

Instantly share code, notes, and snippets.

@aiaio
Created March 19, 2009 21:49
Show Gist options
  • Save aiaio/82089 to your computer and use it in GitHub Desktop.
Save aiaio/82089 to your computer and use it in GitHub Desktop.
module SelectiveAttributeValidatable
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
alias_method_chain :update_attributes, :check
end
end
module InstanceMethods
# Store the set of attributes passed in to #update_attributes.
def update_attributes_with_check(attrs)
@attrs_to_validate = attrs.keys.map(&:to_s)
update_attributes_without_check(attrs)
end
# Returns true if a given attribute was passed in to #update_attributes.
def should_validate?(attr)
if self.new_record?
attrs_to_validate_on_create.include?(attr)
else
@attrs_to_validate.blank? ||
@attrs_to_validate.include?(attr) ||
self.status == 'ENABLED'
end
end
# This method must be overwritten in the class
# where this module is included. Specify whichever
# attributes you want validated on create:
# ['name', 'sku']
def attrs_to_validate_on_create
[]
end
# Allows for the should_validate_x? condition
# in your validations.
def method_missing(method, *args)
if method.to_s =~ /^should_validate_([_\w]+)[?]/
return should_validate?($1)
else
super
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment