Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

A proposal for Actions#gsub_file #217

Closed
wants to merge 1 commit into from

1 participant

@kentaroi

Here is a patch we discussed with @jrochkind on issue #207

In a block of gsub_file, we have no access to capturing groups, which is different from that of String#gsub!. In a block of String#gsub!, we have an access to capturing groups via global variables ($1 etc).

This change would make capturing groups accessible from a block of gsub_file via block parameters, such as:

gsub_file(file_path, regexp) { |*match| match[2].upcase }
gsub_file(file_path, regexp) { |m0, m1, m2| m2.upcase }

the above two lines will get same results.

Also you can use the old style with a single block parameter, such as:

gsub_file(file_path, regexp) { |match| match.gsub(/__/, '').upcase }

However, the following are still not accessible:
1. named capturing groups
2. pre_match
3. post_match

@kentaroi kentaroi A proposal for Actions#gsub_file
This change would make capturing groups accessible from a block of gsub_file.
However, the following are still not accessible:
1. named capturing groups
2. pre_match
3. post_match
46b6d0b
@kentaroi kentaroi closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 29, 2012
  1. @kentaroi

    A proposal for Actions#gsub_file

    kentaroi authored
    This change would make capturing groups accessible from a block of gsub_file.
    However, the following are still not accessible:
    1. named capturing groups
    2. pre_match
    3. post_match
This page is out of date. Refresh to see the latest.
View
10 lib/thor/actions/file_manipulation.rb
@@ -224,7 +224,15 @@ def gsub_file(path, flag, *args, &block)
unless options[:pretend]
content = File.binread(path)
- content.gsub!(flag, *args, &block)
+ if block
+ if block.arity == 1
+ content.gsub!(flag, *args) { block.call($&) }
+ else
+ content.gsub!(flag, *args) { block.call(*$~) }
+ end
+ else
+ content.gsub!(flag, *args)
+ end
File.open(path, 'wb') { |file| file.write(content) }
end
end
View
11 spec/actions/file_manipulation_spec.rb
@@ -248,6 +248,17 @@ def file
File.binread(file).should == "START\nREADME\n__end__\n"
end
+ it "replaces using capturing groups in a block" do
+ action(:gsub_file, "doc/README", /(_+)(start)(_+)/){ |*match| match[2].upcase + match[0] }
+ File.binread(file).should == "START__start__\nREADME\n__end__\n"
+ end
+
+ it "accepts a block which is made from lambda whose arity is one (backwards compat)" do
+ l = lambda{ |match| match.gsub('__', '').upcase }
+ action(:gsub_file, "doc/README", /(_+)(start)(_+)/, &l)
+ File.binread(file).should == "START\nREADME\n__end__\n"
+ end
+
it "logs status" do
action(:gsub_file, "doc/README", "__start__", "START").should == " gsub doc/README\n"
end
Something went wrong with that request. Please try again.