Given I have an AR object (object
) and a string (s
). s
is based out of the associations of object. ie. Product belongs to Aisle, Aisle belongs to Department, Department belongs to Shop
I want to get an array of all those associations. This is what Ive come up with
object = Product.last
s='aisle.department.shop'
new_array = s.split(',').each_with_object([]).with_index do |(assoc_set, array), index|
a = assoc_set.split('.')
a.each_with_index do |assoc, index|
if index == 0
array << object.send(assoc)
elsif index == 1
array << object.send(a[index - 1]).send(a[index])
elsif index == 2
array << object.send(a[index - 2]).send(a[index - 1]).send(a[index])
elsif index == 3
array << object.send(a[index - 3]).send(a[index - 2]).send(a[index - 1]).send(a[index])
end
end
end
Outputs exactly what I want:
[
#<Aisle:0x00007fa001d6f800 ...>,
#<Department:0x00007fa001d44b00 ...>,
#<Shop:0x00007fa020f4bc68 ...>,
]
Except code isnt dynamic. As you can see, it only goes up to 3 levels deep. How can I refactor this?