Created
July 6, 2009 14:59
-
-
Save rgo/141471 to your computer and use it in GitHub Desktop.
Validating non AR models in Rails 2.3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# From http://www.neeraj.name/blog/articles/810-validating-non-activerecord-models-in-rails-2-2 | |
# Modified as said comment 1 - (changed self_and_descendents_from_active_record by self_and_descendants_from_active_record) | |
module Validateable | |
[:save, :save!, :update_attribute].each{|attr| define_method(attr){}} | |
def method_missing(symbol, *params) | |
if(symbol.to_s =~ /(.*)_before_type_cast$/) | |
send($1) | |
end | |
end | |
def self.append_features(base) | |
super | |
base.send(:include, ActiveRecord::Validations) | |
base.extend ClassMethods | |
base.send :include, ActiveSupport::Callbacks | |
base.define_callbacks *ActiveRecord::Validations::VALIDATIONS | |
end | |
module ClassMethods | |
def self_and_descendants_from_active_record | |
klass = self | |
classes = [klass] | |
while klass != klass.base_class | |
classes << klass = klass.superclass | |
end | |
classes | |
rescue | |
[self] | |
end | |
def human_name(options = {}) | |
defaults = self_and_descendants_from_active_record.map do |klass| | |
:"#{klass.name.underscore}" | |
end | |
defaults << self.name.humanize | |
I18n.translate(defaults.shift, {:scope => [:activerecord, :models], :count => 1, :default => defaults}.merge(options)) | |
end | |
def human_attribute_name(attribute_key_name, options = {}) | |
defaults = self_and_descendants_from_active_record.map do |klass| | |
:"#{klass.name.underscore}.#{attribute_key_name}" | |
end | |
defaults << options[:default] if options[:default] | |
defaults.flatten! | |
defaults << attribute_key_name.humanize | |
options[:count] ||= 1 | |
I18n.translate(defaults.shift, options.merge(:default => defaults, :scope => [:activerecord, :attributes])) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment