如何将JSON文件解析为Ruby对象

问题描述 投票:0回答:1

鉴于以下rspec,我正在尝试制作一个从JSON文件读取并将其解析为对象的函数,但这会给我这个错误:

NoMethodError:undefined method `from_json' for Recipe:Class

这是lib / recipe.rb:

require 'json'

class Recipe
  attr_accessor :title, :description, :ingredients, :cook_time, :featured

  def initialize(title:, description:, ingredients:, cook_time:, featured:)
    @title = title
    @description = description
    @ingredients = ingredients
    @cook_time = cook_time
    @featured = featured 
  end

  def from_json(file)
    recipe = JSON.parse(json)
    Recipe.new(recipe)
  end
end

和我的rspec:

 it 'Converts a json into an objeto from recipe type' do
recipe = Recipe.from_json('data/pudim.json')

    expect(recipe.class).to eq Recipe
    expect(recipe.title).to eq 'Pudim'
    expect(recipe.description).to eq 'O melhor pudim da sua vida!'
    expect(recipe.ingredients).to eq 'Leite condensado, ovos e leite'
    expect(recipe.cook_time).to eq 80
    expect(recipe.featured).to eq true
  end

这是data / pudim.json:

{
  "title": "Pudim",
  "description": "O melhor pudim da sua vida!",
  "ingredients": "Leite condensado, ovos e leite",
  "cook_time": 80,
  "featured": true
}

json ruby rspec
1个回答
1
投票

似乎您正在尝试调用类方法,但是您的类中有一个实例方法。

鉴于此,您可以尝试将此方法更改为self.from_json(file)

© www.soinside.com 2019 - 2024. All rights reserved.