1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
def hashify(object_array) h = Hash.new object_array.each do |x| # Required attributes cn = x['contact_name'] hne = x['host_notifications_enabled'] sne = x['service_notifications_enabled'] hnp = x['host_notifications_period'] snp = x['service_notification_period'] hno = x['host_notification_options'] sno = x['service_notification_options'] hnc = x['host_notification_commands'] snc = x['service_notification_commands'] # Optional Attributes ca = x['alias'] if x.include?('alias') email = x['email'] if x.include?('email') pager = x['pager'] if x.include?('pager') csc = x['can_submit_commands'] if x.include?('can_submit_commands') rsi = x['retain_status_information'] if x.include?('retain_status_information') rni = x['retain_nonstatus_information'] if x.include?('retain_nonstatus_information') h[cn] = {:host_notification_enabled => hne, :service_notifications_enabled => sne, :host_notification_period => hnp, :service_notification_period => snp, :host_notification_options => hno, :service_notification_options => sno, :host_notification_commands => hnc, :service_notification_commands => snc } end @contacts = h return h end
Refactorings
No refactoring yet !
Ian Ownbey
April 9, 2008, April 09, 2008 18:33, permalink
Map for proffit
1 2 3 4 5
def hashify(object_hash) new_hash = Hash.new object_hash.map {|x,y| new_hash.merge!({x.to_sym => y})} new_hash end
lusis.myopenid.com
April 10, 2008, April 10, 2008 14:26, permalink
Well I realize later in the day after writing unit tests that I did NOT want to be using symbols there. I'm guessing that means I can change x.to_sym to just x?
I think I have the path I need to follow now.
Many thanks. I don't think I'll forget map anytime soon.
lusis.myopenid.com
April 10, 2008, April 10, 2008 15:27, permalink
This is what the final refactor looked like. It passed my unit tests right off the bat. Thanks again, Ian.
1 2 3 4 5 6 7 8 9 10 11 12
def hashify(object_array) h = Hash.new object_array.each do |x| cd = Hash.new cn = x['contact_name'] x.delete('contact_name') x.map {|y,z| cd.merge!({y => z})} h[cn] = cd end @contacts = h return h end
Ian Ownbey
April 13, 2008, April 13, 2008 04:29, permalink
This should help you out some more.
1 2 3 4 5 6 7 8
def hashify(object_array) @contacts = object_array.inject(Hash.new) do |hash, current| cn = current.delete('contact_name') cd = Hash.new current.map {|y,z| cd.merge!({y => z})} hash[cn] = cd end end
I know this can be done but I'm still a Ruby fledgling. Basically I don't want to have to risk typo errors by having to type new option attributes twice but I need to include them in the hash if the exist. Just seems like a lot of extra typing in both the x.include? as well as down below. Optimally, I'd like to define a list of required attributes and optional attributes that would build the hash.