ruby-on-rails - 将 nokogiri (或任何内部)对象保存到数据库是个好主意吗?

标签 ruby-on-rails ruby database blob nokogiri

我的 Rails 上的 Web 应用程序将一些模型对象的参数存储在 XML 字符串中,因此每当我需要有关特定对象的一些信息时,我都必须解析其 XML 字符串。 XML 的长度很少超过 100 行。但由于我想要优化,我想知道是否可以将解析后的 XML 作为 Nokogiri 的对象存储在数据库中。这是个好主意吗?

最佳答案

虽然可能有异常(exception),但一般来说,您应该避免存储 marshalled objects直接在您的数据库中,除非您有非常充分的理由。就 Nokogiri 而言,如@mu-is-too-short mentioned ,Nokogiri 和 Marshal 在一起玩得不好:

doc = Nokogiri::HTML(some_html)    
Marshal.dump doc
# => TypeError: no _dump_data is defined for class Nokogiri::HTML::Document

也就是说,Marshal#loadMarshal#dump是核心 Ruby 库的一部分,使用起来非常有趣。沿with the docs ,这里是一个快速代码示例,展示了 Marshal 的工作原理,包括一个非常基本的基准测试,将 Marshal.loadClass.new 进行比较:

require 'benchmark'

data_string = <<-DATA
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
DATA

class Example
  attr_reader :data

  def initialize(data)
    @data = data
  end
end

example = Example.new(data_string)

dumped = Marshal.dump example
loaded = Marshal.load dumped

puts "String Bytesize: #{data_string.bytesize} vs. Dump Bytesize: #{dumped.bytesize}"
puts "Marshalled object is larger by #{dumped.bytesize - data_string.bytesize} bytes"

Benchmark.bmbm do |x|
  x.report("Marshal.load: ")  { Marshal.load(dumped).data }
  x.report(" Example.new: ")  { Example.new(data_string).data }
end

关于ruby-on-rails - 将 nokogiri (或任何内部)对象保存到数据库是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17417682/

相关文章:

java - 您可以从 Java 调用已编译的 JRuby 类吗?

ruby-on-rails - 如何找到实例变量的源位置?

mysql - 本地创建数据库时如何指定mySQL主机?

ruby-on-rails - 我可以在 ROR 中使用文本文件作为我的数据库吗?

mysql - 尝试连接到 AWS MySQL 实例时 ActiveRecord NoDatabaseError

ruby-on-rails - 将Rails应用放在公共(public)git中,将私有(private)详细信息保密

mysql - 在 MySQL 中检查时间戳是否来自今天

css - wicked_pdf(使用 wkhtmltopdf)不呈现 Font Awesome 图标

ruby - 在 Ruby 中序列化扩展的 String 类

python - 如何将 Telegram python变量值保存到本地数据库?