0

When parsing a JSON API using ActiveModel::Serializers, is there a way not having to specify every single key in the JSON as attributes?

Say I only need :first_name, :last_name, :country for my views -- unless I also specify the other keys in the JSON, :street_address, :postal_code, :phone, :email, I will get undefined method 'street_address=' for #.

I found http://bigastronaut.com/blog/2014/don-t-serialize-just-a-few-give-me-all-attributes but his PR has not yet been accepted: https://github.com/rails-api/active_model_serializers/pull/535 -- is there something else I could do meanwhile?

class GetFromJson
  include ActiveModel::Serializers::JSON

  attr_accessor :first_name, :last_name, :country # :street_address, :postal_code, :phone, :email

  def attributes=(hash)
    hash.each do |key, value|
      send("#{key}=", value)
    end
  end

  def self.fetch

    # Code to fetch JSON from API

  end
end
Mark Boulder
  • 13,577
  • 12
  • 48
  • 78

1 Answers1

1

I think its always better to directly define what you want in your serializer, but I can see your point that in certain circumstances this could be annoying... one thing you could do, is define all the attr_accessors for every column name in the model, if the serializer is supposed to serialize a specific ActiveRecord model that is.

Say for example you have an AR model named Person, you can find all the database attributes of the object by just writing Person.column_names, this won't give you the virtual attributes you may want, but at least 'gives you all database attributes by default'

So it would be something like:

class PersonSerializer < ActiveModel::Serializer
  Person.column_names.each {|pcn| attributes pcn}

  #...define other virtual attributes here, etc.
end
derekyau
  • 2,936
  • 1
  • 15
  • 14
  • Looks great, but what to do if these attributes come from ones JSON response instead? My use case is here: https://gist.github.com/frankie-loves-jesus/e9dc286ec79834f96c7b – Mark Boulder Aug 03 '14 at 22:21
  • Also I just came across http://bigastronaut.com/blog/2014/don-t-serialize-just-a-few-give-me-all-attributes and consequently https://github.com/rails-api/active_model_serializers/pull/535 -- I reckon that would be more ideal if and when it gets accepted? – Mark Boulder Aug 03 '14 at 22:22
  • 1
    It seems that you are getting the data from a third-party API and then parsing it out in the `fetch` method, perhaps you could just set the attributes from the `keys` method of the returning hash? – derekyau Aug 03 '14 at 22:32