active_model_serializers icon indicating copy to clipboard operation
active_model_serializers copied to clipboard

possibility to render attribute only if attribute is present?

Open krtschmr opened this issue 8 years ago • 3 comments

sometimes we want certain attributes only to be rendered if they are true or if they are not nil

https://github.com/krtschmr/active_model_serializers/commit/92341750417d44016742c0b15ea085797f1dc778 anybody has ambitions to help me, implement this into a merge-request? my current scenario requires that we define it inside the serializer

  def remove_false_attributes
    [:ghosted]
  end

i rather would see something like

remove_false_attributes :ghosted
remove_blank_attributes :ghosted

krtschmr avatar Apr 18 '17 05:04 krtschmr

I'm curious what your use-case is (beside saving a few bytes on the response, which if relevant means you're better off adding compression, leveraging HTTP caching, or ditching JSON altogether for some kind of protobuf).

beauby avatar Apr 18 '17 15:04 beauby

simple reason: we are ghosting comments. due to performance, we still render ghosted comments to all, just with the flag "ghosted" (rendered by react, won't display unless comment.user == current_user).

if there are 100 comments, and 1 is flagged, i only want this particular with "ghosted: true" simply for the reason, that we don't wanna show it too obvious that we are actually /doing/ it. so pretty much just hiding the attribute, in case somebody is looking up requests.


Diese E-Mail wurde von Avast Antivirus-Software auf Viren geprüft. https://www.avast.com/antivirus

krtschmr avatar Apr 18 '17 16:04 krtschmr

@beauby

the following code was working fine. simply remove the attributes if they been false.

in my serializer i added

def remove_false_attributes 
    [:ghosted]
  end

then in my fork i went to the caching method and simply deleted the attributes that are flagged and false.

  attrs = attributes(fields, true)
  
  if self.respond_to?(:remove_blank_attributes)
    self.remove_blank_attributes.each do |blank_attr|
      attrs.delete(blank_attr) if attrs[blank_attr].nil?
    end
  end
  
  if self.respond_to?(:remove_false_attributes)
    self.remove_false_attributes.each do |blank_attr|
      attrs.delete(blank_attr) if attrs[blank_attr] == false
    end
  end
  
  attrs

somehow, i reforked to get current development status and things changed a lot in serializer. i can't find the new place where to put similar code. can you help me? or can we just make it a feature? :)

krtschmr avatar Nov 02 '17 05:11 krtschmr