mardi 11 juillet 2017

Design pattern for attribute wrapper in Ruby on Rails

I am looking for the right way to implement the following in Ruby on Rails 5.1:

I have an ActiveRecord Platform with the attribute structure_xml of type LONGTEXT. 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.

My current solution

A non-ActiveRecord model Structure implements the required methods:

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

The ActiveRecord model initialises this model if needed:

class Platform < ApplicationRecord
  attr_accessor :structure

  def structure
    @structure || (@structure = Structure.new(structure_xml))
  end
  ...
end

It works, but it does not seem ideal to me. What would be the right approach to implement this?

Aucun commentaire:

Enregistrer un commentaire