Empact / roxml

ROXML is a module for binding Ruby classes to XML. It supports custom mapping and bidirectional marshalling between Ruby and XML using annotation-style class methods, via Nokogiri or LibXML.
http://roxml.rubyforge.org/
MIT License
223 stars 176 forks source link

Conditionally combining multiple attributes #45

Open brewpoo opened 12 years ago

brewpoo commented 12 years ago

Using ROXML with dm-core here. I am dealing with a poorly designed XML schema so I need to conditionally set a DM property from one of two xml attributes.


class Sample < Model
  include ROXML
  include DatamMapper::Resource

  xml_name "SAMPLE"
  xml_convention :upcase

  property :name, String
  xml_reader :name

  property :amount, String

  xml_reader :display_amount
  xml_reader :uncast_amount, :from => "AMOUNT"

  def amount
    display_amount || "#{uncast_amount} liters"
  end

end

I was trying to do this via DataMappers after :create hook but this does not get fired until I explicitly save the object. I know I can use a block to set a value but cannot get this to work. In my case AMOUNT is "always" present so I've tried something like:


xml_reader :display_amount
xml_reader(:amount) { |x| x = display_amount || x}

This obviously doesn't work as the block only receives the value returned from xml_reader.

Any suggestions?