I work on a Rails API
, and I want to render some binary in json. To do that I convert my binary in hex to render it.
So I have
#<PlayCard id: 3, card_id: 12, atk: 10, hp: 9, deck_id: nil, game_id: nil, uid: ".dk\x8A", created_at: "2018-06-06 15:17:25", updated_at: "2018-06-06 15:17:25", user_id: 27>
(byebug) play_card.to_json
{"id"=>3, "card_id"=>12, "atk"=>10, "hp"=>9, "deck_id"=>nil, "game_id"=>nil, "uid"=>"2e646b8a", "created_at"=>Wed, 06 Jun 2018 17:17:25 CEST +02:00, "updated_at"=>Wed, 06 Jun 2018 17:17:25 CEST +02:00, "user_id"=>27}
My question is about the rendering of my object. With my method show
I Have no problem but with my method create
I have to call my_object.to_json
did you have an idea ? With out the .to_json
I have a ActionDispatch::TestResponse
object.
def show
record = PlayCard.find_by(id: params[:id])
if record.present?
render json: record.attributes.except('uid'), status: :ok
else
render json: {}, status: :no_content
end
end
def create
play_card = PlayCardsService.create(play_card_params)
if play_card.valid?
render json: play_card.to_json, status: :created
else
render json: { status: 'KO', errors: play_card.errors.full_messages }, status: :unprocessable_entity
end
end
class PlayCardsService
class << self
def create(play_card_params)
PlayCard.create(play_card_params)
end
end
end
def to_json(options = {})
bin = bin_to_hex(self.uid)
self.uid = nil
json = self.as_json
json['uid'] = bin
json
end
def bin_to_hex(s)
s.each_byte.map { |b| b.to_s(16).rjust(2,'0') }.join
end
Thanks for your help
Have a nice day,
Aucun commentaire:
Enregistrer un commentaire