rlperez
rlperez

Reputation: 1328

ActiveModel::Serializers::JSON - How to map an array of JSON from a returned string to an collection of Ruby objects

I have code that works for a single instance but the API I am consuming returns an array of data. I have a class to encapsulate this data:

class Brewery
  include ActiveModel::Serializers::JSON

  attr_accessor :id, :name

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

  def attributes
    instance_values
  end
end

And what the returned data looks like is similar to this

[
    {
        "id": 2,
        "name": "Avondale Brewing Co"
    },
    {
        "id": 44,
        "name": "Trim Tab Brewing"
    }
]

I can marshal a single JSON hash to the class with code such as this:

brewery = Brewery.new
brewery.from_json(single_brewery)

However this doesn't work with the array. I'm relatively new with Ruby so I'm not quite sure what the function to use is or to at least complete the JSON hashes to an array I can map from_json over.

This works but seems clunky

breweries = JSON.parse(brewery_list).map { |b|
  brewery = Brewery.new
  brewery.from_json(b.to_json)
}

Upvotes: 2

Views: 449

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

I am unsure why do you find mapping an array clunky, but you might turn your Brewery to be a factory.

class Brewery
  ...

  def self.many(brewery_list)
    JSON.parse(brewery_list).
         map(&:to_json).
         map(&Brewery.new.method(:from_json)
  end
end

And use it like this

breweries = Brewery.many(brewery_list)

Upvotes: 1

Related Questions