lutaml / lutaml-model

LutaML Model is the Ruby data modeler part of the LutaML data modeling suite. It supports creating serialization object models (XML, YAML, JSON, TOML) and mappings to and from them.
Other
2 stars 2 forks source link

Custom methods and separate model #83

Closed andrew2net closed 1 month ago

andrew2net commented 2 months ago

With separate model custom methods are called on that model:

class Item
  attr_accessor :id
end

class BibItem < Lutaml::Model::Serializable
  model Item
  attribute :id, :string

  xml do
    root 'bibitem'
    map_element "id", to: :id, with: { to: :id_to_xml }
  end

  def id_to_xml(model, doc)
    doc[:did] =  model.id
  end
end

> BibItem.to_xml item
=> lutaml-model-0.3.10/lib/lutaml/model/xml_adapter/xml_document.rb:123:in `add_to_xml': undefined method `id_to_xml' for an instance of Item (NoMethodError)

We shouldn't move serialization methods to separate models.

ronaldtse commented 2 months ago

Thanks @andrew2net for finding this. Indeed the current behavior is incorrect.

@HassanAkbar can you please help? Thanks.

HassanAkbar commented 2 months ago

@ronaldtse Sure, I'm looking into this

ronaldtse commented 2 months ago

Is this now fixed with #86?

HassanAkbar commented 2 months ago

@ronaldtse Just found a minor issue will fix that with the specs in https://github.com/lutaml/lutaml-model/pull/85,

HassanAkbar commented 1 month ago

@ronaldtse I believe this is now fixed. can we close this now?

andrew2net commented 1 month ago

@HassanAkbar with GH version I get this error now:

class Item
  attr_accessor :id
end

class BibItem < Lutaml::Model::Serializable
  model Item
  attribute :id, :string

  xml do
    root 'bibitem'
    map_element "id", to: :id, with: { to: :id_to_xml, from: :id_from_xml }
  end

  def id_to_xml(model, doc)
    doc[:did] =  model.id
  end

  def id_from_xml(model, value)
    model.id = value
  end
end

> item = Item.new
> item.id = '123'
> BibItem.to_xml item
(irb):16:in `id_to_xml': wrong number of arguments (given 3, expected 2) (ArgumentError)
        from /Users/andrej/.rvm/gems/ruby-3.3.3/gems/lutaml-model-0.3.10/lib/lutaml/model/xml_adapter/xml_document.rb:123:in `add_to_xml'

UPD It works. But method id_to_xml should have 3 arguments id_to_xml(model, parent, doc). @HassanAkbar please update README here https://github.com/lutaml/lutaml-model?tab=readme-ov-file#attribute-serialization-with-custom-methods

ronaldtse commented 1 month ago

Closing since done in #92.