2

Say I have two variables (value1 and value2) and either could be nil, how can I create an element using XmlMarkup and only add the attributes that are not nil?

If I do this

xm = Builder::XmlMarkup.new
xm.item(:attribute1=>value1, :attribute2=>value2)

and both value1 and value2 are nil, I still get

<item attribute1="", attribute2=""/>

I have also tried to add the attributes after creating the element but had no success and I cannot figure out if this is even supported.

If it is not already apparent, I am a complete ruby beginner so any input would be appreciated.

1 Answer 1

3

I think something like this could work:

xm = Builder::XmlMarkup.new
attributes = {}
attributes[:attribute1] = value1 if value1
attributes[:attribute2] = value2 if value2
xm.item(attributes)

If you have more than a couple of attributes I can show you a way to minimize duplication with a similar method too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.