使用YAML的JSON而不是ActiveRecord的序列化 [英] ActiveRecord serialize using JSON instead of YAML

查看:161
本文介绍了使用YAML的JSON而不是ActiveRecord的序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于使用YAML的JSON而不是ActiveRecord的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆