tags:

views:

33

answers:

1

Please consider the following context from Innate:

# Default application for Innate
def innate(app = Innate::DynaMap, options = Innate.options)
  roots, publics = options[:roots], options[:publics]

  joined = roots.map{|root| publics.map{|public| ::File.join(root, public)}}

  apps = joined.flatten.map{|pr| Rack::File.new(pr) }
  apps << Current.new(Route.new(app), Rewrite.new(app))

  cascade(*apps)
end

My first question has to do with the following line from the above:

  joined = roots.map{|root| publics.map{|public| ::File.join(root, public)}}

What is this line doing?

1 - My guess is it takes a filename and adds it to a an array caled publics and then wraps that inside another array called roots. Is this correct?

My second question has to do with this:

  apps = joined.flatten.map{|pr| Rack::File.new(pr) }
  apps << Current.new(Route.new(app), Rewrite.new(app))

2 - What is the purpose of "flattening" here?

+2  A: 

It looks like it takes an array (or array-like) thing called roots, and for each element of it, it tacks on each element of publics:

So if roots was ["/a", "/b"] and publics was ["alpha", "beta", "gamma"] it would make:

[["/a/alpha", "/a/beta", "/a/gamma"], ["/b/alpha", "/b/beta", "/b/gamma"]]

Now we can see why it needs to flatten it. Flatten pulls component arrays into one array. So, joined.flatten makes:

["/a/alpha", "/a/beta", "/a/gamma", "/b/alpha", "/b/beta", "/b/gamma"]
DigitalRoss
The thing that's easy to miss is that the type of each element of roots changes during the map block. When handed out, it's an `X`, but then it gives it back as an `Array` of `X`.
DigitalRoss
Or, more precisely, the type of *each element* of `roots` changes during the map to `publics.class`.
DigitalRoss
Thanks. Couldn't see that.
uzo