Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

move dynamic method definitions into ToLang::StringMethods, add docum…

…entation
  • Loading branch information...
commit 0bc5f65c764f3cb3cfb310dac0bd002c9387e8a3 1 parent d78d803
Jimmy Cuadra authored
Showing with 41 additions and 44 deletions.
  1. +1 −44 lib/to_lang.rb
  2. +40 −0 lib/to_lang/string_methods.rb
View
45 lib/to_lang.rb
@@ -23,51 +23,8 @@ class << self
def start(key)
return false if defined?(@connector) && !@connector.nil?
@connector = ToLang::Connector.new(key)
- add_translation_methods
+ String.send(:include, StringMethods)
true
end
-
- private
-
- # Includes ToLang::StringMethods in String and adds dynamic methods
- # by overriding @method_missing@ and @respond_to?@.
- #
- def add_translation_methods
- String.class_eval do
- include StringMethods
-
- def method_missing(method, *args, &block)
- 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 {
- translate(CODEMAP[$1])
- })
-
- send new_method_name
- else
- super
- end
- end
-
- def respond_to?(method, include_private = false)
- if method.to_s =~ /^to_(.*)_from_(.*)$/ && CODEMAP[$1] && CODEMAP[$2]
- true
- elsif method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
- true
- else
- super
- end
- end
- end
- end
end
end
View
40 lib/to_lang/string_methods.rb
@@ -13,5 +13,45 @@ module StringMethods
def translate(target, *args)
ToLang.connector.request(self, target, *args)
end
+
+ # Overrides @method_missing@ to catch and define dynamic translation methods.
+ #
+ # @private
+ #
+ def method_missing(method, *args, &block)
+ 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) do
+ translate(CODEMAP[$1], :from => CODEMAP[$2])
+ end
+
+ 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) do
+ translate(CODEMAP[$1])
+ end
+
+ send new_method_name
+ else
+ super
+ end
+ end
+
+ # Overrides @respond_to?@ to make strings aware of the dynamic translation methods.
+ #
+ # @private
+ #
+ def respond_to?(method, include_private = false)
+ if method.to_s =~ /^to_(.*)_from_(.*)$/ && CODEMAP[$1] && CODEMAP[$2]
+ true
+ elsif method.to_s =~ /^to_(.*)$/ && CODEMAP[$1]
+ true
+ else
+ super
+ end
+ end
end
end

0 comments on commit 0bc5f65

Please sign in to comment.
Something went wrong with that request. Please try again.