使用YAML的JSON而不是ActiveRecord的序列化而不是、序列化、YAML、JSON

2023-09-09 21:58:39 作者:仗剑天涯

我有一个使用序列化列模型:

I have a model that uses a serialized column:

class Form < ActiveRecord::Base
  serialize :options, Hash
end

有没有一种方法,使该序列化使用JSON代替YAML?

Is there a way to make this serialization use JSON instead of YAML?

推荐答案

更新

请参阅下面的一个更合适的Rails> = 3.1的答案中旬的高额定答案。这是Rails的℃的伟大的答案; 3.1。

See mid's high rated answer below for a much more appropriate Rails >= 3.1 answer. This is a great answer for Rails < 3.1.

也许这就是你要找的内容。

Probably this is what you're looking for.

Form.find(:first).to_json

更新

1)安装JSON宝石:

gem install json

2)创建JsonWrapper类

2) Create JsonWrapper class

# lib/json_wrapper.rb

require 'json'
class JsonWrapper
  def initialize(attribute)
    @attribute = attribute.to_s
  end

  def before_save(record)
    record.send("#{@attribute}=", JsonWrapper.encrypt(record.send("#{@attribute}")))
  end

  def after_save(record)
    record.send("#{@attribute}=", JsonWrapper.decrypt(record.send("#{@attribute}")))
  end

  def self.encrypt(value)
    value.to_json
  end

  def self.decrypt(value)
    JSON.parse(value) rescue value
  end
end

3)加入模型回调:

3) Add model callbacks:

#app/models/user.rb

class User < ActiveRecord::Base
    before_save      JsonWrapper.new( :name )
    after_save       JsonWrapper.new( :name )

    def after_find
      self.name = JsonWrapper.decrypt self.name
    end
end

4)测试一下吧!

4) Test it!

User.create :name => {"a"=>"b", "c"=>["d", "e"]}

PS:

这不是很干,但我尽力了。如果任何人都可以修复 after_find 用户模式,这将是巨大的。

PS:

It's not quite DRY, but I did my best. If anyone can fix after_find in User model, it'll be great.