title: Design pattern for attribute wrapper in Ruby on Rails
body: <p>I am looking for the right way to implement the following in Ruby on Rails 5.1:</p>
  
  <p>I have an ActiveRecord <strong>Platform</strong> with the attribute <code>structure_xml</code> of type <em>LONGTEXT</em>. It contains pure XML. I would like to add a wrapper with helper methods to query the XML (using Nokogiri), e.g. to find certain nodes or to validate it.</p>
  
  <p><strong>My current solution</strong></p>
  
  <p>A non-ActiveRecord model <strong>Structure</strong> implements the required methods:</p>
  
  <pre><code>def Structure   
    def initialize(xml)
      @xml_root = Nokogiri::XML(xml).root
    end
  
    def get_node_by_id(node_id)
      @xml_root.xpath(".//Node[@id='#{node_id}']").first
    end
    ...
  end
  </code></pre>
  
  <p>The ActiveRecord model initialises this model if needed:</p>
  
  <pre><code>class Platform &lt; ApplicationRecord
    attr_accessor :structure
  
    def structure
      @structure || (@structure = Structure.new(structure_xml))
    end
    ...
  end
  </code></pre>
  
  <p>It works, but it does not seem ideal to me. What would be the right approach to implement this?</p>