Created
March 18, 2016 13:38
-
-
Save arturictus/2774cbd879176b07dbe6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# In not working!! | |
# Validations are added, but errors are not in the errors list after valid | |
module AddChildValidations | |
extend ActiveSupport::Concern | |
class_methods do | |
# Example: | |
# class User < ActiveRecord::Base | |
# has_one :address | |
# add_child_validations_for :address do | |
# validates_presence_of :address, :city, :postal_code, :state, :state_code, | |
# :country_code | |
# end | |
# end | |
def add_child_validations_for(name, opts= {}, &block) | |
fail "No block provided for child validations on #{self.class}:#{name}" unless block | |
@_child_validations ||= {} | |
@_child_validations[name.to_sym] = opts.merge(name: name, block: block) | |
self.send(:alias_method, "_old_#{name}=", "#{name}=") | |
self.send(:alias_method, "_old_#{name}", name) | |
reader_line, reader = __LINE__, "def #{name} | |
return @#{name} if @#{name} | |
block = _get_child_validations_for('#{name}')[:block] | |
_old_#{name}.singleton_class.instance_exec(&block) | |
@#{name} ||= _old_#{name} | |
end" | |
writer_line, writer = __LINE__, "def #{name}=(input) | |
@#{name} = nil | |
self._old_#{name} = input | |
end" | |
class_eval reader, __FILE__, reader_line | |
class_eval writer, __FILE__, writer_line | |
end | |
end | |
def _child_validations | |
self.class.instance_variable_get(:@_child_validations) || {} | |
end | |
def _get_child_validations_for(name) | |
_child_validations[name.to_sym] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment