Reputation: 6870
I'm storing some recipe instances in a CSV file like this:
def add_recipe(recipe)
CSV.open(@filepath, 'ab', @csv_options) do |csv|
csv << [recipe, recipe.name, recipe.description, false]
end
end
with recipe
being an intense of my Recipe
class.
In the file, I have something like this:
"#<Recipe:0x007fee9bbbab48>", "name1", "description1", "false"
"#<Recipe:0x007fee9bbbab49>", "name2", "description2", "false"
The issue is that when I want to retrieve the object stored in each row with row[0]
or the boolean with row[2]
, I get a string containing the object or the boolean.
How can I get the object with its original class which is Recipe or boolean but not as a string?
Upvotes: 0
Views: 1465
Reputation: 15515
What you have stored in the first column is the result of recipe.to_s
, which is nothing more than a string with the class type and an encoding of the object id. This is not the same as a serialized object.
You have to write each attribute of the recipes as you have already done, and not write recipe
itself to a line.
csv << [recipe.id, recipe.name, recipe.description, recipe.other_attribute]
Upvotes: 1
Reputation: 168131
You cannot. It is impossible with CSV (unless you invent your own serialization method for CSV). .........................
Upvotes: 1