diff options
author | Aaron Patterson <aaron.patterson@gmail.com> | 2011-02-01 09:34:21 -0800 |
---|---|---|
committer | Aaron Patterson <aaron.patterson@gmail.com> | 2011-02-01 14:25:46 -0800 |
commit | 3cc2b77dc1cb4c1e5cfac68c7828e35a27415e0d (patch) | |
tree | a4c0ff4344492bfaed687e1321e7bb8511933e97 /activerecord/lib | |
parent | 0171de00b7a21b9f2866f600fe2aca3152608e33 (diff) | |
download | rails-3cc2b77dc1cb4c1e5cfac68c7828e35a27415e0d.tar.gz rails-3cc2b77dc1cb4c1e5cfac68c7828e35a27415e0d.tar.bz2 rails-3cc2b77dc1cb4c1e5cfac68c7828e35a27415e0d.zip |
adding a YAML Column coder for YAML serialization to db columns
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record.rb | 4 | ||||
-rw-r--r-- | activerecord/lib/active_record/coders/yaml_column.rb | 34 |
2 files changed, 38 insertions, 0 deletions
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb index c80bce2849..5afb97803e 100644 --- a/activerecord/lib/active_record.rb +++ b/activerecord/lib/active_record.rb @@ -81,6 +81,10 @@ module ActiveRecord autoload :Validations end + module Coders + autoload :YAMLColumn, 'active_record/coders/yaml_column' + end + module AttributeMethods extend ActiveSupport::Autoload 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 |