Skip to content

Commit

Permalink
Bound and unbound callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
Vladimir Tikhonov committed Mar 17, 2015
1 parent 955b838 commit ae591f2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/regexy/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def bound(method = :both)
if method == :right || method == :both
new_regexp.concat('\z')
end
new_regexp = additional_bound(method, new_regexp)
::Regexy::Regexp.new(new_regexp, options)
end

Expand All @@ -53,6 +54,7 @@ def unbound(method = :both)
if method == :right || method == :both
new_regexp.sub!(/\\z\s*\z/, '')
end
new_regexp = additional_unbound(method, new_regexp)
::Regexy::Regexp.new(new_regexp, options)
end

Expand All @@ -65,6 +67,14 @@ def normalize_regexp(regexp, *args)
else regexp
end
end

def additional_bound(method, regex) # You can override this methods if your regular expression needs additional bound/unbound logic
regex
end

def additional_unbound(method, regex)
regex
end
end

class RegexpWithMode < ::Regexy::Regexp
Expand Down
24 changes: 24 additions & 0 deletions spec/regexp_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@
end

context '#bound' do
class BoundCallbackCheck < Regexy::Regexp
protected

def additional_bound(method, regex)
"#{method.to_s}/#{regex}"
end
end

it 'prepends \A to regexp when method is :left' do
expect(Regexy::Regexp.new(/foo/).bound(:left)).to eq /\Afoo/
end
Expand All @@ -118,9 +126,21 @@
it 'preserves regexp options' do
expect(Regexy::Regexp.new(/foo/i).bound).to eq /\Afoo\z/i
end

it 'calls #additional_bound callback' do
expect(BoundCallbackCheck.new(/foo/).bound).to eq /both\/\Afoo\z/
end
end

context '#unbound' do
class UnboundCallbackCheck < Regexy::Regexp
protected

def additional_unbound(method, regex)
"#{method.to_s}/#{regex}"
end
end

it 'removes leading \A when method is :left' do
expect(Regexy::Regexp.new(/\Afoo/).unbound(:left)).to eq /foo/
end
Expand All @@ -136,6 +156,10 @@
it 'preserves regexp options' do
expect(Regexy::Regexp.new(/\Afoo\z/i).unbound).to eq /foo/i
end

it 'calls #additional_unbound callback' do
expect(UnboundCallbackCheck.new(/\Afoo\z/).unbound).to eq /both\/foo/
end
end
end

Expand Down

0 comments on commit ae591f2

Please sign in to comment.