纯ruby类的验证

时间:2015-08-20 15:16:35

标签: ruby validation activerecord activemodel

我有两节课;客户和预订。我的项目只包含ruby代码,而不是rails项目。

类保留逐行读取批量json文件,其中包括客户哈希。

从那个哈希中,我创建了客户对象。

这是预订类中的代码。

gotRemoteDescription

在customer.rb中我有以下内容;

    def parse_json
        File.open(@filename, "r" ).each do |line|    
            @customers << Customer.new(JSON.parse(line), @coordinates)
        end

        return @customers
    end

在Reservation类中创建Customer对象时遇到2个问题;

第一个是,我对“validates_presence_of”方法有nomethod错误;

require 'active_model' 

class Customer 

    include ActiveModel::Validations

    validates_presence_of :hash, :coordinates
    attr_reader :name, :userid, :latitude, :longitude, :distance  

    def initialize(hash, coordinates)
        @userid = hash['user_id']
        @name = hash['name']
        @latitude = convert_degree_to_radian(hash['latitude'].to_f)
        @longitude = convert_degree_to_radian(hash['longitude'].to_f)
        @distance = calculate_distance(coordinates['latitude'], coordinates['longitude'])
    end

第二个是,因为我用`block in validate': undefined method `coordinates' for #<Customer:0x007ff6631d6698> (NoMethodError) 方法创建新对象。它不会检查验证。例如,如果我发送nil对象,在initialize方法中,我将没有nil类的方法错误。

在纯ruby代码中创建这些对象时,我应该如何处理验证?

感谢。

1 个答案:

答案 0 :(得分:1)

我认为这可能是因为您的Customer类中没有名为coordinates的方法。

尝试将其添加到attr_reader

attr_reader :name, :userid, :latitude, :longitude, :distance, :coordinates