Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if one path is under another path in Ruby?

Tags:

ruby

I have two paths: application root path and target path. What is the simplest way to ensure that the target path is the children of application root path?

Basically the target path provided by the user is to be displayed by my server. But I want to constrain my server so only the files under the application root path are displayable. So I want to check that the target path is under the root path.

The root path can contain nested directories.

like image 479
lulalala Avatar asked Jan 21 '14 15:01

lulalala


1 Answers

Another way:

def child?(root, target)
  raise ArgumentError, "target.size=#{target.size} < #{root.size} = root.size"\
    if target.size < root.size

  target[0...root.size] == root &&
    (target.size == root.size || target[root.size] == ?/)
end

root = "/root/app"

p child?(root, "/root/app/some/path") # => true
p child?(root, "/root/apple")         # => false 
p child?(root, "/root/app")           # => true
p child?(root, "/root")               # => ArgumentError: target.size = 5 < 9 = root.size
like image 114
Cary Swoveland Avatar answered Oct 16 '22 15:10

Cary Swoveland