2012-06-04 76 views
1

我如何驗證Ruby中的attr?我如何驗證Ruby中的屬性

我的文件airplane.rb

class Airplane 

include Validatable 

attr_reader :aircraft_type, :weight 
attr_accessor :speed, :altitude, :course 

def initialize(aircraft_type, options={}) 
    @aircraft_type = aircraft_type.to_s 
    @course     = options[:course]  || random_course 
    @weight   = options[:weight]  || rand(1...1000) 
    @speed   = options[:speed]  || rand(1...500) 
    @apltitude  = options[:apltitude] || rand(50...3000) 
    @position_x   = options[:position_x] || rand(1...3000) 
    @position_y   = options[:position_y] || rand(1...3000) 
    check_course 
end 

def position 
@position = [@position_x, @position_y] 
end 

def check_course 
if @course < 1 
    @course = 1 
    puts "Invalid course. Set min" 
elsif @course > 360 
    @course = 360 
    puts "Invalid course. Set max" 
else 
    @course = @course 
    end 
end 

def random_course 
@course = rand(1..360) 
end 

末,所有值都必須進行檢查

module Validatable 

@@validations={} 
# I need receive = {presence: [:weight, :length], aircraft_type: [:length]} 

def self.validates_presence_of(*attrs) 
    @@validations[:presence] = attrs 
end 

def validate 
    @@validations.each do |v, fields| 
     fields.each {|field_name| self.send("validate_#{v}_of", field_name)} 
    end 
end 

private 

    def validate_presence_of(field_name) 
    end 

我的文件初始化

我的文件validatable.rb。 rb with airplanes attr

airplane1 = Airplane.new("Boeing 74", course: 600, speed: 300, apltitude: 300) 
airplane2 = Airplane.new("Boeing 700", course: 250, speed: 300, apltitude: 300) 
airplane3 = BigAirplane.new("Boeing 707", weight: 50, speed: 300, apltitude: 400) 

我該如何完成validatable.rb來驗證每架飛機的每個值?

+0

當您實例化對象時,您正在使用默認值加載它。因此,如果用戶以後專門將其更改爲零,則它們將僅爲零。請更好地解釋流程。另外,你有沒有看過rails activerecord驗證?您可以包含它,而無需ORM的其餘部分。 – Anil

回答

1

使用ActiveModel ::驗證而不是重新發明車輪。

參見:

http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ 

http://www.rubyinside.com/rails-3-0s-activemodel-how-to-give-ruby-classes-some-activerecord-magic-2937.html 

http://asciicasts.com/episodes/211-validations-in-rails-3 

好運。

+0

好的。但需要在我的方式:)))validate_presence_of 什麼需要檢查負數 – Savroff

+0

@Savroff列出無效數據和您想要查看的消息的示例。 – Anil

+0

無效如果 i.to_s /// i <0 – Savroff