Permalink
Browse files

Allow calling private methods on template names

This is an expected feature from Thor. When rendering files,
Thor behaves like Sinatra. It works as if the file was embedded
in the current Thor class. Therefore, restricting the filename
to be just public methods is a wrong limitation that does not
fit with how Thor is meant to be used.
  • Loading branch information...
1 parent 1c7cb62 commit 3c5a459eb0f27410d632734994f805b1e3484acd @josevalim josevalim committed Mar 26, 2013
Showing with 13 additions and 34 deletions.
  1. +3 −19 lib/thor/actions/empty_directory.rb
  2. +0 −4 lib/thor/error.rb
  3. +10 −11 spec/actions/empty_directory_spec.rb
@@ -97,28 +97,12 @@ def destination=(destination)
#
# user.rb
#
- # The method referenced by %-string SHOULD be public. Otherwise you
- # get the exception with the corresponding error message.
+ # The method referenced can be either public or private.
#
def convert_encoded_instructions(filename)
filename.gsub(/%(.*?)%/) do |initial_string|
- call_public_method($1.strip) or initial_string
- end
- end
-
- # Calls `base`'s public method `sym`.
- # Returns:: result of `base.sym` or `nil` if `sym` wasn't found in
- # `base`
- # Raises:: Thor::PrivateMethodEncodedError if `sym` references
- # a private method.
- def call_public_method(sym)
- if base.respond_to?(sym)
- base.send(sym)
- elsif base.respond_to?(sym, true)
- raise Thor::PrivateMethodEncodedError,
- "Method #{base.class}##{sym} should be public, not private"
- else
- nil
+ method = $1.strip
+ base.respond_to?(method, true) ? base.send(method) : initial_string
end
end
View
@@ -25,8 +25,4 @@ class RequiredArgumentMissingError < InvocationError
class MalformattedArgumentError < InvocationError
end
-
- # Raised when a user tries to call a private method encoded in templated filename.
- class PrivateMethodEncodedError < Error
- end
end
@@ -107,24 +107,23 @@ def base
expect(@action.send(:convert_encoded_instructions, "%file_name%.txt")).to eq("expected.txt")
end
+ it "accepts and executes a private %\w+% encoded instruction" do
+ @action.base.extend Module.new {
+ private
+ def private_file_name
+ "expected"
+ end
+ }
+ expect(@action.send(:convert_encoded_instructions, "%private_file_name%.txt")).to eq("expected.txt")
+ end
+
it "ignores an 'illegal' %\w+% encoded instruction" do
expect(@action.send(:convert_encoded_instructions, "%some_name%.txt")).to eq("%some_name%.txt")
end
it "ignores incorrectly encoded instruction" do
expect(@action.send(:convert_encoded_instructions, "%some.name%.txt")).to eq("%some.name%.txt")
end
-
- it "raises an error if the instruction refers to a private method" do
- module PrivExt
- private
- def private_file_name
- "something_hidden"
- end
- end
- @action.base.extend(PrivExt)
- expect { @action.send(:convert_encoded_instructions, "%private_file_name%.txt") }.to raise_error Thor::PrivateMethodEncodedError
- end
end
end
end

0 comments on commit 3c5a459

Please sign in to comment.