Sha256: bb2d8c5ad03ca4953a68027b1138629fc5014a5528a4cc3ebd737ba9ee647ff5

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 KB

Contents

module TestModel
  extend  ActiveSupport::Concern

  included do
    extend  ActiveModel::Translation
    include ActiveModel::Validations
    include ActiveModel::AttributeMethods
    include DynamicMethods

    attribute_method_suffix ""
    attribute_method_suffix "="
    cattr_accessor :model_attributes
  end

  module ClassMethods
    def define_method_attribute=(attr_name)
      generated_attribute_methods.module_eval("def #{attr_name}=(new_value); @attributes['#{attr_name}']=self.class.type_cast(new_value); end", __FILE__, __LINE__)
    end

    def define_method_attribute(attr_name)
      generated_attribute_methods.module_eval("def #{attr_name}; @attributes['#{attr_name}']; end", __FILE__, __LINE__)
    end

    def type_cast(value)
      return value unless value.is_a?(String)
      value.to_time rescue nil
    end
  end

  module DynamicMethods
    def method_missing(method_id, *args, &block)
      if !self.class.attribute_methods_generated?
        self.class.define_attribute_methods self.class.model_attributes.map(&:to_s)
        method_name = method_id.to_s
        send(method_id, *args, &block)
      else
        super
      end
    end
  end

  def initialize(attributes = nil)
    @attributes = self.class.model_attributes.inject({}) do |hash, column|
      hash[column.to_s] = nil
      hash
    end
    self.attributes = attributes unless attributes.nil?
  end

  def attributes
    @attributes.keys
  end

  def attributes=(new_attributes={})
    new_attributes.each do |key, value|
      send "#{key}=", value
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
validates_timeliness-3.0.0.beta.3 spec/test_model.rb