GTranslate

- 2009-01-04 09:40:59

I finally wrapped up some code I've been meaning to write for a while, its a wrapper for the Google Translate API. Its also the first serious time I've used method_missing in a class, in this case its to add methods for translating between all the various languages.

Its fairly simple to use, there is an examples.rb included with it, but the basic usage is just this:

# Convert from english to french
Google::Translate.english_to_french( "Hello" ) # => "Bonjour"

# There is also a short(er)-hand version
Google::Tr.en_to_fr( "Hello" )

As per usual with all my code its available on my github account, as the GTranslate project. I'll throw some specs together for it and package it up as a gem soon.

5 Comments on GTranslate

  1. Wondering why didn't:

    class Tr < Translate; end
    

    Instead of:

    const_set "Tr", Translate
    

    It is shorter, I know. But wouldn't it feel more object-y-esque..er... you know?

  2. @Dmondark:

    I honestly hadn't considered using inheritance to create the Tr class, rather than just using Kernal#const_set. I think mainly it was because I had the train of thought, if I was doing this with a method I'd use alias_method, so how do I do alias_class in effect. Did a quick google and came up with const_set.

    However, having just knocked up some example code, I think I'd rather use const_set here rather than subclassing, because it uses the original classname. Heres an example that illustrates it rather better than I can articulate in words:

    # Create the first class
    class Foo
      # returns the name of the class
      def self.klass
        self.to_s
      end
    end
    
    # Create second class by subclassing
    class Bar  Foo; end
    
    # Create third class with const_set
    Kernel.const_set "Sed", Foo
    
    # And then call the method on each class
    Foo.klass # => "Foo"
    Bar.klass # => "Bar"
    Sed.klass # => "Foo"
    

    As you can see, even though we call Sed.klass it still returns "Foo" as the classname, therefore its just an alias to the original class, rather than a whole new class inheriting from the original one.

    I'm sure there is a difference between the two methods, and certainly if I wanted to add any methods or anything to Tr, then I would subclass Translate, but seeing as I just want an alias pointing to the original class, I think I'll leave it using const_set.

  3. That makes sense. Thanks a bunch for the extensive explanation :)

  4. ...and inspired py-gtranslate ;-)

  5. Nice one Will.


About You

Comment