Rails: possible to check if a string is binary?

In a particular Rails application, I'm pulling binary data out of LDAP into a variable for processing. Is there a way to check if the variable contains binary data? I don't want to continue with processing of this variable if it's not binary. I would expect to use is_a? ...

In fact, the binary data I'm pulling from LDAP is a photo. So maybe there's an even better way to ensure the variable contains binary JPEG data? The result of this check will determine whether to continue processing the JPEG data, or to render a default JPEG from disk instead.


There is actually a lot more to this question than you might think. Only since Ruby 1.9 has there been a concept of characters (in some encoding) versus raw bytes. So in Ruby 1.9 you might be able to get away with requesting the encoding. Since you are getting stuff from LDAP the encoding for the strings coming in should be well known, most likely ISO-8859-1 or UTF-8.

In which case you can get the encoding and act on that:

some_variable.encoding # => when ASCII-8BIT, treat as a photo

Since you really want to verify that the binary data is a photo, it would make sense to run it through an image library. RMagick comes to mind. The documentation will show you how to verify that any binary data is actually JPEG encoded. You will then also be able to store other properties such as width and height.

If you don't have RMagick installed, an alternative approach would be to save the data into a Tempfile, drop down into Unix (assuming you are on Unix) and try to identify the file. If your system has ImageMagick installed, the identify command will tell you all about images. But just calling file on it will tell you this too:

~/Pictures$ file P1020359.jpg 
P1020359.jpg: JPEG image data, EXIF standard, comment: "AppleMark"

You need to call the identify and file commands in a shell from Ruby:

%x(identify #{tempfile})
%x(file #{tempfile})
链接地址: http://www.djcxy.com/p/25308.html

上一篇: 虾模板无法正常工作

下一篇: Rails:可以检查一个字符串是否是二进制的?