I have two classes; customer and reservation. And my project is consist of only ruby code, not rails project.
Class reservation reads bulk json file line by line which includes customer hash.
From that hash, I create customer object.
Here's the code within the reservation class.
def parse_json
File.open(@filename, "r" ).each do |line|
@customers << Customer.new(JSON.parse(line), @coordinates)
end
return @customers
end
And in customer.rb I have the following;
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
I have 2 problems while creating Customer object in Reservation class;
The first one is, I'm having nomethod error for "validates_presence_of" method;
`block in validate': undefined method `coordinates' for #<Customer:0x007ff6631d6698> (NoMethodError)
The second one is, since I'm creating new objects with new
method. It does not check the validations. For example, if I send nil objects, in initialize method, I'll get no method error for nil class.
How should I handle validations while creating those objects in pure ruby code?
Thanks.