Rails: why is calling to_a on a string not valid i

2019-04-27 09:01发布

I'm trying to decrypt a bunch of passwords for a database migration. I've got some older Rails code (actually a Runner script) that decrypts them just fine. But putting that same code into a Rake task causes the task to fail with ...undefined method `to_a' for "secretkey":String...

Why would calling to_a on a string be invalid in a Rake task, but perfectly valid in a 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)

5条回答
做个烂人
2楼-- · 2019-04-27 09:25

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

查看更多
3楼-- · 2019-04-27 09:25

If you are parsing to a serialization object to use on apis, you could:

JSON.parse "[]" # => []
查看更多
叼着烟拽天下
4楼-- · 2019-04-27 09:36

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

You can use:

"foo".chars.to_a

Which results in:

["f","o","o"]
查看更多
Emotional °昔
5楼-- · 2019-04-27 09:49

To duplicate the 1.8.7 functionality:

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

You would use:

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

The other answers suggest #chars, which is not the same:

1.9.9 > 'foo'.chars.to_a # => ['f', 'o', 'o']
查看更多
爷、活的狠高调
6楼-- · 2019-04-27 09:51
"abcd".each_char.map {|c| c }
查看更多
登录 后发表回答