I have a Skill model, which has many prerequisites (or prereqs in my model), and I need to create a map N-levels deep of the prerequisites for a skill, because I need to pass this information to Javascript (with the gon gem in my controller) for some crazy, HTML5/KineticJS action that shows the birds eye view of the relationship between this skill and others.
Right now, the code below is working great to consistently map 5 levels deep.
delegate :url_helpers, to: 'Rails.application.routes'
def prereqs_map
prereqs_array = [ self.title.to_s, url_helpers.skill_path(self), Array.new(prereqs) ]
prereqs_array[2] = prereqs_array[2].map do |prereq1|
prereq1 = [ prereq1.title.to_s, url_helpers.skill_path(prereq1), Array.new(prereq1.prereqs).map do |prereq2|
prereq2 = [ prereq2.title.to_s, url_helpers.skill_path(prereq2), Array.new(prereq2.prereqs).map do |prereq3|
prereq3 = [ prereq3.title.to_s, url_helpers.skill_path(prereq3), Array.new(prereq3.prereqs).map do |prereq4|
prereq4 = [ prereq4.title.to_s, url_helpers.skill_path(prereq4), Array.new(prereq4.prereqs).map do |prereq5|
prereq5 = [ prereq5.title.to_s, url_helpers.skill_path(prereq5), [] ]
end ] # prereq depth 5
end ] # prereq depth 4
end ] # prereq depth 3
end ] # prereq depth 2
end # prereq depth 1
return prereqs_array
end
The problem, as you can see, is it’s super messy with nested maps and there’s no way that I can figure out to pass a depth parameter and have the method map out to whatever depth I pass it.
I figure there has to be a better way of doing this. Any thoughts?
Try this: