ruby - 纯 ruby 类的验证

标签 ruby validation activerecord activemodel

我有两个类(class);客户和预订。我的项目只包含 ruby​​ 代码,而不是 rails 项目。

类保留逐行读取包含客户哈希的批量 json 文件。

从该散列中,我创建了客户对象。

这是预订舱位中的代码。

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

        return @customers
    end

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

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

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

第一个是“validates_presence_of”方法没有方法错误;

`block in validate': undefined method `coordinates' for #<Customer:0x007ff6631d6698> (NoMethodError)

第二个是,因为我正在使用 new 方法创建新对象。它不检查验证。例如,如果我在初始化方法中发送 nil 对象,我将不会收到 nil 类的方法错误。

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

谢谢。

最佳答案

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

尝试将它添加到您的 attr_reader

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

关于ruby - 纯 ruby 类的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32122100/

相关文章:

ruby-on-rails - 使用 rbenv 安装的 ruby​​ 上的段错误

Ruby RJB 无法创建 Java VM 错误

ruby - minitest - 将任何参数传递给 expect

使用 REGEX 和 .split() 的 Java XML validator

php - 为什么 Yii2 的 ActiveRecord 使用大量单个 SELECT 而不是 JOIN?

postgresql - 使用 activerecord + postgres 获取 hstore 列的平均值

ruby-on-rails - spree 安装问题 - 使用 RVM

python - 我应该对我的 python 函数/方法进行多少输入验证?

java - 根据格式将字符串日期验证为有效日期的最佳方法是什么?

php - 使用 Codeigniter 的 ActiveRecord 语法构建包含 UNION 和子查询的 SELECT 查询