如何在 Rails 中持久保存对象
我正在实现一种 ruby 在线终端(仅供练习)。我正在一个简单的 js Web 应用程序中使用 AJAX 来调用评估“终端”输入的方法。为了避免环境问题并让用户创建自己的对象,我使用了“绑定”对象。问题是我不知道如何保留绑定。
我的第一个想法是创建一个在用户每次访问应用程序时在帖子请求之间持续存在的绑定。此时,将使用唯一键和新绑定创建键-对象对。然后将密钥传递给客户端。当用户通过ajax发送要评估的字符串时,我发送密钥。然后,我可以获得绑定对象并更新它。
我尝试了类似的操作:
class TerminalController
@@bindings = {}
def index
@token = keyToken
@@bindings[@token] = getBinding
end
private
def keyToken
Digest::MD5.hexdigest(Time.now.to_s)
end
def getBinding
# declare methods for all bindings
# ...
binding
end
end
但在执行时,代码无法创建键值对。事实上,我在该行之后尝试执行的任何操作都会失败。我不明白为什么。
实际上,我认为如果我可以序列化绑定,它就会起作用,但我认为它可能效率低下,因为网络延迟和绑定的可能增长。
I'm implementing a kind of ruby online terminal (just for practice). I am using AJAX from a simple js web application to call a method that evals the input of the "terminal". To avoid problems with the environment and let the user creates his own objects, i was using a "binding" object. The problem is that i don't know how to persist the bindings.
My first idea was to create a bindindg that persists between posts requests for each time a user access to the application. In that moment, a key-object pair is created with a unique key and a new binding. The key is then passed to the client. When the user sends the string to evaluate via ajax, i send the key. Then, i can get the binding object and update it.
I tried something like:
class TerminalController
@@bindings = {}
def index
@token = keyToken
@@bindings[@token] = getBinding
end
private
def keyToken
Digest::MD5.hexdigest(Time.now.to_s)
end
def getBinding
# declare methods for all bindings
# ...
binding
end
end
But in execution time, the code fails creating the key-value pair. In fact, anything that i try to execute after that line fails. I don't understand why.
Actually, i think if i can serialize the binding it will work, but i think it can be inefficient because the network latency and the posible growth of the binding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,我认为在大多数 Ruby 实现中没有办法序列化绑定。如果您尝试 Marshal.dump 绑定,您会在 MRI 中收到 TypeError (Marshal 是 Ruby 中用于序列化对象的内置库。
可能还有更多其他方法可以完成您想做的事情。但是,如果您必须序列化绑定,请查看 MagLev。该实现的设计使得任何对象都可以被持久化。
Unfortunately I don't think there is a way to serialize a binding in most Ruby implementations. If you try to Marshal.dump a binding you get a TypeError in MRI (Marshal is the built-in library for serializing objects in Ruby).
There may be more other ways of doing what you're trying to do. However, if you must serialize a binding then take a look at MagLev. That implementation is designed so that any object can be persisted.