Permalink
Browse files

define magic methods the first time they're called

  • Loading branch information...
1 parent 4c26f80 commit 76776d0dfee22d7a32d955bc61b4ebcc6afce7fa @jimmycuadra jimmycuadra committed Dec 26, 2010
Showing with 20 additions and 1 deletion.
  1. +7 −1 lib/to_lang.rb
  2. +13 −0 spec/to_lang_spec.rb
View
@@ -17,7 +17,13 @@ def add_magic_methods
String.class_eval do
def method_missing(method, *args, &block)
if method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
- self.translate(CODEMAP[$1])
+ new_method_name = "to_#{$1}".to_sym
+
+ self.class.send(:define_method, new_method_name, Proc.new {
+ translate(CODEMAP[$1])
+ })
+
+ send new_method_name
else
super
end
View
@@ -45,5 +45,18 @@
"hello_world".should respond_to "to_#{language}"
end
end
+
+ context "when a magic method has been called once" do
+ before :each do
+ ToLang.connector.stub(:request)
+ "hello world".to_spanish
+ 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
+ end
+ end
end
end

0 comments on commit 76776d0

Please sign in to comment.