Fu8*_*u86 13 ruby gem encoding ruby-on-rails
有没有String.force_encoding()在Ruby 1.8.7(或Rails 2.x)中使用的解决方案,以便它像在Ruby 1.9中一样工作?我读了一些关于require的内容active_support,但这不起作用
$> gem list --local | grep'rails\| activesupport'
 activesupport (3.0.3, 2.3.8, 2.3.5)
 rails (2.3.8, 2.3.5)
$> ruby -v
ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-darwin10.4.0]
$> rails -v
Rails 2.3.8
IRB:
> require "rubygems"
=> true 
> require "active_support"
=> true 
> "asdf".force_encoding("UTF-8")
NoMethodError: undefined method `force_encoding' for "asdf":String
> String.respond_to?(:force_encoding)
=> false
Sea*_*ere 21
这将在Ruby 1.8.7和Ruby 1.9中为您提供String#to_my_utf8:
require 'iconv'
class String
  def to_my_utf8
    ::Iconv.conv('UTF-8//IGNORE', 'UTF-8', self + ' ')[0..-2]
  end
end
然后...
?> "asdf".to_my_utf8
=> "asdf"
灵感来自Paul Battley,还记得我在remote_table gem上的一些旧作.
The*_*heo 14
唯一force_encoding确实的1.9是它改变了字符串的编码领域,它实际上并没有修改字符串的字节数.
Ruby 1.8没有字符串编码的概念,所以force_encoding将是一个无操作.如果您希望能够在1.8和1.9中运行相同的代码,可以像这样自己添加:
class String
  def force_encoding(enc)
    self
  end
end
当然还有其他一些事情需要做,以使编码在1.8和1.9中的工作方式相同,因为它们处理这个问题的方式截然不同.
| 归档时间: | 
 | 
| 查看次数: | 19008 次 | 
| 最近记录: |