我有两个类(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/