Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/pg-xml/activerecord.rb

Class Method Summary collapse

Class Method Details

.has_xml_column(attr_name) ⇒ Object

define the has_xml_column :col_name name



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/pg-xml/activerecord.rb', line 14

def self.has_xml_column attr_name
  
  # serialize using the custom serializer
  serialize attr_name, ActiveRecord::Coders::XML
  # validate XML before saving
  validate "validate_#{attr_name}_xml"
  
  # define the attribute writer to accept a string
  # and convert it to XML
  define_method("#{attr_name}=") do |val|
    if val.is_a? String
      val = PgXML.load(val)
    end
    self[attr_name] = val
  end
  
  # validate XML before writing to database
  define_method("validate_#{attr_name}_xml") do
    # TODO make this work with hpricot
    return true if self[attr_name].nil? || self[attr_name].errors == []
    self[attr_name].errors.each do |e|
      errors.add(attr_name, e.to_s)
    end
    return false
  end
  
end