0

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))
        end

        return @customers
    end

And in customer.rb I have the following;

    validates_presence_of :hash
    validate :hash_should_include_all_fields
    attr_reader :name, :userid, :latitude, :longitude, :distance  

    def hash_should_include_all_fields
        puts "I'm here #{hash}"
        if hash.assert_valid_keys('user_id', 'name', 'latitude', 'longitude')
            puts "Valid"
        else
            puts "Not valid"
        end
    end

However as I create customer objects, hash_should_include_all_fields method is not called.

What do I miss in here, that would be great if you can help.

Thanks

CanCeylan
  • 2,890
  • 8
  • 41
  • 51

1 Answers1

2

You're calling new which will build a Customer object but do nothing more.

Calling create! or create will also run validations and write the Object to the database if it's an active_record model.

If you don't want to write it to the databas you can call valid? on the instance created with new

Axel Tetzlaff
  • 1,355
  • 8
  • 11
  • also `save` run validation. – Roman Kiselenko Aug 20 '15 at 12:19
  • Hi Axel, thank you for your answer, but regarding calling "new" for creating instance, validates_presence_of also does not work. So when I give nil parameters to customer class, it also gave "no method error for nil class". So what's the best way to create those objects? – CanCeylan Aug 20 '15 at 12:31
  • I dont know what you mean by 'parameters to customer class'? 'The best way' really depends on more than one can tell by the few lines shown. Here is a slightly more detailed answer on new vs. create http://stackoverflow.com/questions/4333163/question-about-create-and-new-methods-in-activerecord-class – Axel Tetzlaff Aug 20 '15 at 13:12
  • what I'm saying is, calling Customer.new(). If some those parameters are nil, then I'll get error on initialize method. – CanCeylan Aug 20 '15 at 13:17
  • That's a different problem. Post a new question with more context of the stack trace where exactly this error occurs – Axel Tetzlaff Aug 20 '15 at 13:27