Search code examples
rubymotion

Rubymotion: NoMethodError for added method


I added an extra method to the String class. I want to use this method later on, but I get a no Method error.

class String
   def as_file_full_path
      NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)   [0].stringByAppendingPathComponent(self)    
  end
end

When I try the following in the REPL it works:

 (main)> "image.jpg".as_full_path
  => "/Users/user/Library/Application Support/iPhone Simulator/6.1/Applications/30D186A9-B1C7-4377-AE91-0D14BD3B4A6D/Documents/image.jpg"

But when I call a method on a my model class, it does not work anymore:

 (main)> w = Word.first
  => #<Word:0x94d7df0>
 (main)> w.filename
  => "2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf"
 (main)> w.filename.class
  => String
 (main)> w.filename.as_full_path
 2013-02-28 09:17:55.935 project[74283:c07] undefined method `as_full_path' for "2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf":String (NoMethodError)
 => NoMethodError: undefined method `as_full_path' for "2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf":String

The model is implemented using NanoStore::Model.

Edit:

When I clone the String returned by the model, the added method is present.

w.filename.dup.as_full_path
=> "/Users/user/Library/Application Support/iPhone Simulator/6.1/Applications/30D186A9-B1C7-4377-AE91-0D14BD3B4A6D/Documents/2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf"

Solution

  • Problem solved! For some reason extending the String class does not always work. I think the NanoStore for some reason does not return "real" ruby strings. Solved it by replacing "String" with "NSString" so:

    class NSString 
       def as_file_full_path
           NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)   [0].stringByAppendingPathComponent(self)    
       end
    end