Sha256: fdb965131f003e4f8e04a8279a70325f1ddd65f081596f894bfedeb9e3e0efb5

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

require "va/version"

module Va
  class Model
    attr_reader :attributes

    def initialize(args={})
      @attributes = {}
      args.each do |k, v|
        key = k.to_sym
        @attributes[key] = v if self.class.keys.include?(key)
      end
    end

    def valid?
      self.class.validations.all? { |attrs, validation|
        validation.call(*attrs.map { |attr| self.send(attr)})
      }
    end

    private
    def self.validations
      @validations ||= []
    end

    def self.validate(*attrs, &block)
      attrs.each do |attr|
        raise UnknownAttribute unless keys.include?(attr)
      end
      validations << [attrs, block]
    end

    def self.validate_present(*attrs)
      attrs.each do |attr|
        validate(attr) do |a|
          a && a != ""
        end
      end
    end
    
    def self.keys
      @keys ||= []
    end

    def self.attribute(attr_name)
      name = attr_name.to_sym

      self.keys << name

      define_method "#{name}=" do |value|
        attributes[name] = value
      end

      define_method "#{name}" do
        attributes[name]
      end
    end
  end
  class UnknownAttribute < Exception; end
end


Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
va-0.1.1 lib/va.rb
va-0.1.0 lib/va.rb