繁体   English   中英

如何在不使用数据库的情况下将 Ruby object 存储在我的 Rails 应用程序中?

[英]How do I store a Ruby object in my Rails app without using a database?

给定

  • 这 Ruby class:

     class Quiz attr_accessor:topic, :course, :highest_grade, :failing_grade, :answers_by_questions def initialize(topic, course, highest_grade, failing_grade) @topic = topic @course = course @highest_grade = highest_grade @failing_grade = failing_grade @answers_by_questions = Hash.new() end def add_question(question, answer) @answers_by_questions[question] = answer end end
  • 这个测验 class 的实例:

     ch1_history_quiz = Quiz.new("Chapter 1", "History", 100, 65) ch1_history_quiz.add_question("Which ancient civilisation created the boomerang?", "Aboriginal Australians")

客观的

保存此测验 object 以供该应用程序的所有用户稍后访问。


问题

如何在 Rails 6.0 中存储和访问这个测验 object 而不在数据库中表示它?


可能的解决方案

  • 是否可以使用 Marshal 腌制 object 并保存以备后用?

到目前为止我检查过的内容

SO - Store json object in ruby on rails app : Because this is JSON, going back and forth between the JSON format and the parsed format is more intuitive.

SO - 我可以创建 ruby 类的数据库吗? : 这个问题我真的没有答案。 一些链接已损坏。 不过,我认为这个问题非常相似。

是否可以使用 Marshal 腌制 object 并保存以备后用?

是的,使用与示例相同的代码,您可以序列化和反序列化 object 以恢复原样。

irb(main):021:0> marshalled = Marshal.dump(ch1_history_quiz)
=> "\x04\bo:\tQuiz\n:\v@topicI\"\x0EChapter 1\x06:\x06ET:\f@courseI\"\fHistory\x06;\aT:\x13@highest_gradeii:\x13@failing_gradeiF:\x1A@answers_by_questions{\x06I\"6Which ancient civilisation created the boomerang?\x06;\aTI\"\eAboriginal Australians\x06;\aT"
irb(main):022:0> deserialized = Marshal.load(marshalled)
=> #<Quiz:0x00007f81d3995348 @topic="Chapter 1", @course="History", @highest_grade=100, @failing_grade=65, @answers_by_questions={"Which ancient civilisation created the boomerang?"=>"Aboriginal Australians"}>

另一种更具可读性的选择是将 object 序列化为 YAML 格式:

irb(main):030:0> yamled = YAML.dump(ch1_history_quiz)
=> "--- !ruby/object:Quiz\ntopic: Chapter 1\ncourse: History\nhighest_grade: 100\nfailing_grade: 65\nanswers_by_questions:\n  Which ancient civilisation created the boomerang?: Aboriginal Australians\n"
irb(main):031:0> deserialized = YAML.load(yamled)
=> #<Quiz:0x00007f81d398cb80 @topic="Chapter 1", @course="History", @highest_grade=100, @failing_grade=65, @answers_by_questions={"Which ancient civilisation created the boomerang?"=>"Aboriginal Australians"}>

使用这两个选项中的任何一个,您都可以稍后将其保存在 DB 文本字段中(有足够的空间来保存大对象)、纯文本文件或您选择的任何内容。
此外,需要记住的非常重要的一点是有关使用 marshal 或 yaml的安全问题,因此必须始终从受信任的来源加载对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM