Skip to content

Commit

Permalink
added regexpmatch() YCP built-in
Browse files Browse the repository at this point in the history
  • Loading branch information
lslezak committed Jan 23, 2013
1 parent a015ee3 commit ddc4c6b
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/ruby/ycp/builtins.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require "ycp/path"
require "ycp/helper"

module YCP
module Builtins
Expand Down Expand Up @@ -43,6 +44,14 @@ def self.splitstring string, sep
string.split /[#{Regexp.escape sep}]/, -1 * 2**20
end

# regexpmatch() YCP built-in
def self.regexpmatch string, regexp
return nil if string.nil? || regexp.nil?

ruby_regexp = YCP::Helper.ruby_regexp regexp
!string.match(ruby_regexp).nil?
end

# tolower() YCP built-in
def self.tolower string
return nil if string.nil?
Expand Down
15 changes: 15 additions & 0 deletions src/ruby/ycp/helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

module YCP
module Helper

# helper for transforming YCP regexps to Ruby regexps
# replace YCP regexp metacharacters by Ruby ones
# ^ -> \A, $ -> \z
def self.ruby_regexp reg_str
return nil if reg_str.nil?

reg_str.gsub(/\A\^/, '\\A').gsub(/\$\z/, '\\z')
end

end
end
10 changes: 10 additions & 0 deletions tests/ruby/builtins_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ def test_splitstring
assert_equal ["text", "with", "different", "separators"], YCP::Builtins.splitstring("text/with:different/separators", "/:")
end

def test_regexpmatch
assert_equal nil, YCP::Builtins.regexpmatch(nil, nil)
assert_equal nil, YCP::Builtins.regexpmatch("", nil)
assert_equal true, YCP::Builtins.regexpmatch("", "")
assert_equal true, YCP::Builtins.regexpmatch("abc", "")

assert_equal true, YCP::Builtins.regexpmatch("abc", "^a")
assert_equal true, YCP::Builtins.regexpmatch("abc", "c$")
end

def test_tolower
assert_equal nil, YCP::Builtins.tolower(nil)
assert_equal "", YCP::Builtins.tolower("")
Expand Down
16 changes: 16 additions & 0 deletions tests/ruby/helper_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
$LOAD_PATH << File.dirname(__FILE__)
require "test_helper"

require "ycp/helper"

class HelperTest < YCP::TestCase

def test_ruby_regexp
assert_equal "", YCP::Helper.ruby_regexp("")
assert_equal "\\A", YCP::Helper.ruby_regexp("^")
assert_equal "\\z", YCP::Helper.ruby_regexp("$")
assert_equal "\\A\\z", YCP::Helper.ruby_regexp("^$")
assert_equal "\\Aabcd\\z", YCP::Helper.ruby_regexp("^abcd$")
end

end

0 comments on commit ddc4c6b

Please sign in to comment.