nesquena/rabl — Issue #154: Best way to clean ou blank/null attributes?
Author: TimBrunsmo
Created: 2012-01-26 15:26:45+00:00
State: open

In my particular use case I can't be sure that an attribute is set if it is passed.
What i need is a way to clean out attributes that is blank or null.

It's easy to do when constructing a custom node like this:

````
node :user do |u|
data = {
:name => u.name,
:description => u.description,
:slug => u.title,
:id => u.id,
:likes => u.likes
}

data.keep_if {|key, value| value.present?}
end
````
But when not using this the view becomes cluttered with a lot of if statements:

````
node :attr1, :if => lambda { |r| r.attr1.present? } do |r|
r.attr1
end

node :attr2, :if => lambda { |r| r.attr2.present? } do |r|
r.attr2
end

node :attr3, :if => lambda { |r| r.attr3.present? } do |r|
r.att3
end

node :attr4, :if => lambda { |r| r.attr4.present? } do |r|
r.attr4
end
````
I've tried this:

````
attribute :attr1, :if => lambda { |r| r.attr1.present? }

attribute :attr2, :if => lambda { |r| r.attr2.present? }

attribute :attr3, :if => lambda { |r| r.attr3.present? }

attribute :attr4, :if => lambda { |r| r.attr4.present? }
````
This is a litte cleaner but does not work, when an attribute is nil it returns `"att1":null`
Is there a better way of doing this?
Maybe it's not meant to be done in rabl, but rather before it gets passed to rabl template?