Skip to content

Commit

Permalink
Added String#to_path and Array#to_path
Browse files Browse the repository at this point in the history
  • Loading branch information
Luca Guidi committed Jul 10, 2008
1 parent 9bb9a3a commit 989d094
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/sashimi/core_ext/array.rb
@@ -0,0 +1,21 @@
class Array
# Transform the current +Array+ to a path.
# It's an alias for +File#join+
#
# %w(path to app).to_path # => path/to/app
# %w(path to app).to_path(true) # => /Users/luca/path/to/app
def to_path(absolute = false)
path = File.join(self)
path = File.expand_path(path) if absolute
path
end

# Transform the current +Array+ to an absolute path.
#
# %w(path to app).to_absolute_path # => /Users/luca/path/to/app
# %w(path to app).to_abs_path # => /Users/luca/path/to/app
def to_absolute_path
to_path(true)
end
alias_method :to_abs_path, :to_absolute_path
end
13 changes: 13 additions & 0 deletions lib/sashimi/core_ext/string.rb
@@ -0,0 +1,13 @@
class String
# Transform the current +String+ to a system path,
# according to the current platform file system.
#
# "path/to/app".to_path # => path/to/app (on *nix)
# "path/to/app".to_path # => path\to\app (on Windows)
#
# "path/to/app".to_path(true) # => /Users/luca/path/to/app (on *nix)
# "path/to/app".to_path(true) # => C:\path\to\app (on Windows)
def to_path(absolute = false)
self.split(/\/\\/).to_path(absolute)
end
end
22 changes: 22 additions & 0 deletions test/unit/core_ext/array_test.rb
@@ -0,0 +1,22 @@
require 'test/unit'
require 'test/test_helper'

class ArrayTest < Test::Unit::TestCase
uses_mocha 'ArrayTest' do
def setup
File.stubs(:SEPARATOR).returns '/'
end

def test_to_path
assert_equal 'path/to/app', %w(path to app).to_path
end

def test_to_absolute_path
actual = File.dirname(__FILE__)
expected = File.expand_path actual
assert_equal expected, actual.split(File::SEPARATOR).to_path(true)
assert_equal expected, actual.split(File::SEPARATOR).to_absolute_path
assert_equal expected, actual.split(File::SEPARATOR).to_abs_path
end
end
end
20 changes: 20 additions & 0 deletions test/unit/core_ext/string_test.rb
@@ -0,0 +1,20 @@
require 'test/unit'
require 'test/test_helper'

class StringTest < Test::Unit::TestCase
uses_mocha 'StringTest' do
def setup
File.stubs(:SEPARATOR).returns '/'
end

def test_to_path
assert_equal 'path/to/app', 'path/to/app'.to_path
end

def test_to_absolute_path
actual = File.dirname(__FILE__)
expected = File.expand_path actual
assert_equal expected, actual.to_path(true)
end
end
end

0 comments on commit 989d094

Please sign in to comment.