0

I receive from external service JSON with trainings information for my current_user(by email).

{
    “id:”5357c5d17303b5357c5d173078”,
    “email”:”some@email.com”,
    ”trainings”:[
        {
            “training_id“: “5357c4e5d61f15357c4e5d622f“,
            “name”: ”training 1”,
            “state”: “started”
        },
        {
            “training_id“: “5357af490fcda5357af490fd15“,
            “name”: ”training 2”,
            “state”: “finished”
        }
    ]
}

I want to parse this JSON and present it on my page. So I thought about presenter.

class EducationPresenter
  attr_reader :email, :trainings

  def initialize json
    @email = json['email']
    @trainings = json['trainings']
  end
end

and

so now I can use it in my views like that:

Email: <%= @presenter.email %>
<% @presenter.trainings.each do |training| %>
Training: <%= training['training_id'] %>
<% end %>

How I can also parse and convert JSON to some Object to be able to use it like that:

@presenter.training.each {|t| t.state }

Is the presenter god way to handle that?

tomekfranek
  • 6,852
  • 8
  • 45
  • 80

1 Answers1

0

Use JSON::parse :

class EducationPresenter
  attr_reader :presneter

  def initialize json
    json_hash = JSON.parse(json)
    @presneter = OpenStruct.new(
                                email: json_hash['email'],
                                trainings: json_hash['trainings']
                               )
  end
end

Read Parsing JSON to understand this and also OpenStruct.

Now you create your object,

 @education_presenter = EducationPresenter.new(json_string)

And view :

Email: <%= @education_presenter.presenter.email %>
<% @education_presenter.presenter.trainings.each do |training| %>
Training: <%= training['training_id'] %>
<% end %>
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317