jeudi 2 avril 2015

Initialize Array of hashes using a struct

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


Aucun commentaire:

Enregistrer un commentaire