0

I am receiving an array of parameters [config['events']] that looks like this:

 [{"event"=>"loaded", "tags"=>["videjbajc_jbad"]}, {"event"=>"clicked"}, 
 {"event"=>"downloaded"}, {"url"=>"http://aintnothingbutarailsthing"}....}]

I am trying to run validations on each hash key, this should be dynamic since the input might change, hash key name stay the same.

First step - call events method to map each array of hashes:

   def valid?
        @errors = []
        @errors << 'Please check events unless self.events.all?(&:valid?)
        @errors.empty?
   end

second step - run map to my Events class

   def events
         @events ||= (config['events'] || []).map { |e| Event.create(e) }
   end

Final step - receive data array object and proceed to initialize and validate

  class Event < Struct.new(
                        :event,
                        :link_type,
                        :url,
                        :media_id,
                        ....  
                      )

   def self.create(data)
      self.new(     
            data['event'],
            data['link_type'],
            data['url'],
            data['media_id'],
            ...
          )
     end

      validates :event, :presence => true
      validates :url, :allow_nil => true, :format => /https:/
      .. and so on and so forth.. :-)
 end

Problem: Not sure what I am doing wrong here. I can only initialize the event key. Putting in a raise after self.create(data) #{data.inspect} will return

       {"event"=>"loaded", "tags"=>["amex_video_q3_delivered"]}

:event will validate okay, but tags will not and everything else too.. :-(

Please advise :-)

2
  • What exactly is your question? Commented Apr 3, 2015 at 1:59
  • How to correctly initialize my array of hashes using the struct mentioned above? Commented Apr 3, 2015 at 2:12

1 Answer 1

1

I figured it out. When passing my array of parameters i had to account for every possible key value pair condition.

I initialized it like this:

            data['event'],
            data['tags'] ? data['tags'] : nil,
            data['link_type'],
            data['url'],
            data['media_id'],
            data['ad_placement'] ? data['ad_placement'] : nil,
            data['points'] ? data['points'].to_i : nil,
            data['award'] ? data['award'] : nil,               
            data['points_tag'] ? data ['points_tag'] : nil,
            data['track'] ? data['track'] : nil,
            data['checkin_completed_ttl'] ? data['checkin_completed_ttl'] : nil

making sure to expect a nil value for certain keys.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.