From 3cc2b77dc1cb4c1e5cfac68c7828e35a27415e0d Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Feb 2011 09:34:21 -0800 Subject: adding a YAML Column coder for YAML serialization to db columns --- .../lib/active_record/coders/yaml_column.rb | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 activerecord/lib/active_record/coders/yaml_column.rb (limited to 'activerecord/lib/active_record/coders') diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb new file mode 100644 index 0000000000..9b0df119ef --- /dev/null +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -0,0 +1,34 @@ +module ActiveRecord + # :stopdoc: + module Coders + class YAMLColumn + RESCUE_ERRORS = [ ArgumentError ] + + if defined?(Psych) && defined?(Psych::SyntaxError) + RESCUE_ERRORS << Psych::SyntaxError + end + + attr_accessor :object_class + + def initialize(object_class = Object) + @object_class = object_class + end + + def load(yaml) + return yaml unless yaml.is_a?(String) && yaml =~ /^---/ + begin + obj = YAML::load(yaml) + + unless obj.is_a?(object_class) || obj.nil? + raise SerializationTypeMismatch, + "Attribute was supposed to be a #{object_class}, but was a #{obj.class}" + end + + rescue *RESCUE_ERRORS + yaml + end + end + end + end + # :startdoc +end -- cgit v1.2.3