Permalink
Browse files

add to_lang_from_lang magic methods

  • Loading branch information...
1 parent 91ec284 commit b163c312b4f625588c05af6a3748d8d38cbb8b0f @jimmycuadra jimmycuadra committed Dec 26, 2010
Showing with 26 additions and 4 deletions.
  1. +12 −2 lib/to_lang.rb
  2. +14 −2 spec/to_lang_spec.rb
View
14 lib/to_lang.rb
@@ -18,7 +18,15 @@ def start(key)
def add_magic_methods
String.class_eval do
def method_missing(method, *args, &block)
- if method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
+ if method.to_s =~ /^to_(.*)_from_(.*)$/ && CODEMAP[$1] && CODEMAP[$2]
+ new_method_name = "to_#{$1}_from_#{$2}".to_sym
+
+ self.class.send(:define_method, new_method_name, Proc.new {
+ translate(CODEMAP[$1], :from => CODEMAP[$2])
+ })
+
+ send new_method_name
+ elsif method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
new_method_name = "to_#{$1}".to_sym
self.class.send(:define_method, new_method_name, Proc.new {
@@ -32,7 +40,9 @@ def method_missing(method, *args, &block)
end
def respond_to?(method, include_private = false)
- if method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
+ if method.to_s =~ /^to_(.*)_from_(.*)$/ && CODEMAP[$1] && CODEMAP[$2]
+ true
+ elsif method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
true
else
super
View
16 spec/to_lang_spec.rb
@@ -39,27 +39,39 @@
end
ToLang::CODEMAP.each do |language, code|
+ it "will respond_to :to_#{language}" do
+ "hello_world".should respond_to "to_#{language}"
+ end
+
+ it "will respond to :to_#{language}_from_english" do
+ "hello_world".should respond_to "to_#{language}_from_english"
+ end
+
it "translates to #{language} when sent :to_#{language}" do
ToLang.connector.stub(:request)
ToLang.connector.should_receive(:request).with("hello world", code)
"hello world".send("to_#{language}")
end
- it "will then respond_to? :to_#{language}" do
- "hello_world".should respond_to "to_#{language}"
+ it "translates to #{language} from english when sent :to_#{language}_from_english" do
+ ToLang.connector.stub(:request)
+ ToLang.connector.should_receive(:request).with("hello world", code, :from => 'en')
+ "hello world".send("to_#{language}_from_english")
end
end
context "when a magic method has been called once" do
before :each do
ToLang.connector.stub(:request)
"hello world".to_spanish
+ "hello world".to_spanish_from_english
end
it "defines the method and does not call :method_missing the next time" do
string = "hello world"
string.should_not_receive(:method_missing)
string.to_spanish
+ string.to_spanish_from_english
end
end
end

0 comments on commit b163c31

Please sign in to comment.