Sha256: 0c70a3d0947700edfd063b4b70b4d8d60965e36e13a0c2c8a88909911072449c

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

module ValidatesTimeliness
  module AttributeMethods
    extend ActiveSupport::Concern

    included do
      class_inheritable_accessor :timeliness_validated_attributes
      self.timeliness_validated_attributes = []
    end

    module ClassMethods

      public
      # Override in ORM shim
      def timeliness_attribute_timezone_aware?(attr_name)
        false
      end

      # Override in ORM shim
      def timeliness_attribute_type(attr_name)
        :datetime
      end

      protected

      def define_timeliness_methods(before_type_cast=false)
        return if timeliness_validated_attributes.blank?
        timeliness_validated_attributes.each do |attr_name|
          define_timeliness_write_method(attr_name)
          define_timeliness_before_type_cast_method(attr_name) if before_type_cast
        end
      end

      def define_timeliness_write_method(attr_name)
        type = timeliness_attribute_type(attr_name)
        timezone_aware = timeliness_attribute_timezone_aware?(attr_name)

        method_body, line = <<-EOV, __LINE__ + 1
          def #{attr_name}=(value)
            @timeliness_cache ||= {}
            @timeliness_cache["#{attr_name}"] = value
            #{ "value = ValidatesTimeliness::Parser.parse(value, :#{type}, :timezone_aware => #{timezone_aware}) if value.is_a?(String)" if ValidatesTimeliness.use_plugin_parser }
            super
          end
        EOV
        class_eval(method_body, __FILE__, line)
      end

      def define_timeliness_before_type_cast_method(attr_name)
        method_body, line = <<-EOV, __LINE__ + 1
          def #{attr_name}_before_type_cast
            _timeliness_raw_value_for('#{attr_name}')
          end
        EOV
        class_eval(method_body, __FILE__, line)
      end
    end

    module InstanceMethods
      def _timeliness_raw_value_for(attr_name)
        @timeliness_cache && @timeliness_cache[attr_name.to_s]
      end

      def _clear_timeliness_cache
        @timeliness_cache = {}
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
validates_timeliness-3.0.0.beta.4 lib/validates_timeliness/attribute_methods.rb