Rails: why are you calling to_a on a line that is invalid in the rake task?

I am trying to decrypt a bunch of passwords for database migration. I have old Rails code (actually a Runner script) that decrypts them just fine. But including the same code in the Rake task causes the task to crash with ... undefined method `to_a 'for" secretkey ": String ...

Why is the call to_a in a string not valid in the Rake task, but it works fine in the Runner script?

require 'openssl' KEY = 'secretkey' namespace :import do task :users => :environment do def decrypt_password(pw) cipher = OpenSSL::Cipher::Cipher.new('bf-ecb') cipher.decrypt cipher.key = KEY.to_a.pack('H*') <<--------- FAILS RIGHT HERE on to_a data = data.to_a.pack('H*') data = cipher.update(data) data << cipher.final unpad(data) end end ... other methods end 

(Rails 3.0.0, Ruby 1.9.2)

+7
source share
5 answers

In ruby โ€‹โ€‹1.9, String no longer has a to_a method. Your old code probably used Ruby 1.8, which did.

+12
source

To duplicate 1.8.7 functionality:

 1.8.7 > 'foo'.to_a # => ['foo'] 

Would you use:

 1.9.3 > 'foo'.lines.to_a # => ['foo'] 

Other answers suggest #chars, which is not the same:

 1.9.9 > 'foo'.chars.to_a # => ['f', 'o', 'o'] 
+16
source

String objects do not have to_a . Take a look here: http://ruby-doc.org/ruby-1.9/classes/String.html

You can use:

 "foo".chars.to_a 

Result:

 ["f","o","o"] 
+7
source
 "abcd".each_char.map {|c| c } 
+1
source

If you are analyzing a serialization object for use on apis, you can:

 JSON.parse "[]" # => [] 
0
source

All Articles