Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to access wrap child elements #106

Open
fidalgo opened this issue Nov 11, 2018 · 1 comment
Open

How to access wrap child elements #106

fidalgo opened this issue Nov 11, 2018 · 1 comment

Comments

@fidalgo
Copy link

fidalgo commented Nov 11, 2018

I'm creating a XML serializer, that comes after a mapper and a validator, and they share the same methods, so a code method exists in both mapper and validator. To avoid manually creating every field, I'm using some metaprogramming to set the values on the XML serializer, when I use a wrap I cannot set the child elements.

I have the following the following class:

require 'happymapper'

class Country
  include HappyMapper

  element :code, String
  element :name, String
end

class Profile
  include HappyMapper

  element :country, Country
  element :name, String
end

class User
  include HappyMapper

  wrap 'PersonalInformation' do
    has_many :profiles, Profile
  end
  element :name, String
end

I need to access the elements of PersonalInformation so I've tried:

User.new.class.elements

=> [#<HappyMapper::Element:0x0000558f73aed438
  @method_name="PersonalInformation",
  @name="PersonalInformation",
  @options={:single=>true, :name=>"PersonalInformation"},
  @tag="PersonalInformation",
  @type=#<Class:0x0000558f73aee3d8>,
  @xml_type="element">,
 #<HappyMapper::Element:0x0000558f73aece20
  @method_name="name",
  @name="name",
  @options={:single=>true, :name=>"name"},
  @tag="name",
  @type=String,
  @xml_type="element">]

But since the PersonalInformation it's an element itself, I don't have a way to find it's child elements. Am I missing something?

@fidalgo fidalgo changed the title How to access wrap elements How to access wrap child elements Nov 11, 2018
@mvz
Copy link
Owner

mvz commented Dec 2, 2020

You can call #type on the first element to get its class. This is an anonymous class generated by the wrap method to represent the PersonalInformation:

pry(main)> User.elements.first.type.elements
=> [#<HappyMapper::Element:0x000055b6dd2724e8
  @method_name="profiles",
  @name="profiles",
  @options={:single=>false, :name=>"profiles"},
  @tag="profiles",
  @type=Profile,
  @xml_type="element">]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants