mirror of
https://github.com/ditkrg/validates_timeliness.git
synced 2026-01-25 07:16:41 +00:00
methods for validated attributes for write cache and before type cast
cache raw value in @attributes_cache which is AR convention but should work fine with non-AR ORM before type cast method for reading back cached raw value
This commit is contained in:
@@ -29,13 +29,17 @@ module ValidatesTimeliness
|
||||
# Setup method for plugin configuration
|
||||
def self.setup
|
||||
yield self
|
||||
extend_classes.each {|klass| klass.send(:include, ValidatesTimeliness::HelperMethods) }
|
||||
extend_classes.each {|klass|
|
||||
klass.send(:include, ValidatesTimeliness::HelperMethods)
|
||||
klass.send(:include, ValidatesTimeliness::AttributeMethods)
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
require 'validates_timeliness/conversion'
|
||||
require 'validates_timeliness/validator'
|
||||
require 'validates_timeliness/helper_methods'
|
||||
require 'validates_timeliness/attribute_methods'
|
||||
require 'validates_timeliness/extensions'
|
||||
require 'validates_timeliness/version'
|
||||
|
||||
|
||||
43
lib/validates_timeliness/attribute_methods.rb
Normal file
43
lib/validates_timeliness/attribute_methods.rb
Normal file
@@ -0,0 +1,43 @@
|
||||
module ValidatesTimeliness
|
||||
module AttributeMethods
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
included do
|
||||
attribute_method_suffix "_before_type_cast"
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
|
||||
protected
|
||||
|
||||
def define_method_attribute=(attr_name)
|
||||
if timeliness_validated_attributes.include?(attr_name)
|
||||
method_body, line = <<-EOV, __LINE__ + 1
|
||||
def #{attr_name}=(value)
|
||||
@attributes_cache ||= {}
|
||||
@attributes_cache["_#{attr_name}_before_type_cast"] = value
|
||||
super
|
||||
end
|
||||
EOV
|
||||
class_eval(method_body, __FILE__, line)
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
def define_method_attribute_before_type_cast(attr_name)
|
||||
if timeliness_validated_attributes.include?(attr_name)
|
||||
method_body, line = <<-EOV, __LINE__ + 1
|
||||
def #{attr_name}_before_type_cast
|
||||
@attributes_cache && @attributes_cache["_#{attr_name}_before_type_cast"]
|
||||
end
|
||||
EOV
|
||||
class_eval(method_body, __FILE__, line)
|
||||
else
|
||||
super rescue(NoMethodError)
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -20,5 +20,15 @@ module ValidatesTimeliness
|
||||
validates_with Validator, _merge_attributes(attr_names).merge(:type => :datetime)
|
||||
end
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
def timeliness_validated_attributes
|
||||
@timeliness_validated_attributes ||= begin
|
||||
_validators.map do |attr_name, validators|
|
||||
attr_name.to_s if validators.any? {|v| v.is_a?(ValidatesTimeliness::Validator) }
|
||||
end.compact
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user