本文簡要介紹ruby語言中 PStore類
的用法。
PStore
實現了基於 Hash
的基於文件的持久性機製。用戶代碼可以按名稱(鍵)將 Ruby 對象(值)的層次結構存儲到數據存儲文件中。對象層次結構可能隻是一個對象。用戶代碼稍後可能會根據需要從數據存儲中讀回值,甚至更新數據。
事務行為確保任何更改一起成功或失敗。這可用於確保數據存儲不會處於臨時狀態,其中一些值已更新但其他值未更新。
在幕後,Ruby 對象使用 Marshal
存儲到數據存儲文件中。這具有通常的局限性。例如, Proc
對象無法編組。
使用示例:
require "pstore"
# a mock wiki object...
class WikiPage
def initialize( page_name, author, contents )
@page_name = page_name
@revisions = Array.new
add_revision(author, contents)
end
attr_reader :page_name
def add_revision( author, contents )
@revisions << { :created => Time.now,
:author => author,
:contents => contents }
end
def wiki_page_references
[@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
end
# ...
end
# create a new page...
home_page = WikiPage.new( "HomePage", "James Edward Gray II",
"A page about the JoysOfDocumentation..." )
# then we want to update page data and the index together, or not at all...
wiki = PStore.new("wiki_pages.pstore")
wiki.transaction do # begin transaction; do all of this or none of it
# store page...
wiki[home_page.page_name] = home_page
# ensure that an index has been created...
wiki[:wiki_index] ||= Array.new
# update wiki index...
wiki[:wiki_index].push(*home_page.wiki_page_references)
end # commit changes to wiki data store file
### Some time later... ###
# read wiki data...
wiki.transaction(true) do # begin read-only transaction, no changes allowed
wiki.roots.each do |data_root_name|
p data_root_name
p wiki[data_root_name]
end
end
交易方式
默認情況下,隻有在操作係統(和底層硬件)不引發任何意外 I/O 錯誤的情況下,才能確保文件完整性。如果在 PStore
寫入文件時發生 I/O 錯誤,則文件將損壞。
您可以通過設置 pstore.ultra_safe = true
來防止這種情況。但是,這會導致輕微的性能損失,並且僅適用於支持原子文件重命名的平台。有關詳細信息,請參閱ultra_safe
的文檔。
相關用法
- Ruby PStore.commit用法及代碼示例
- Ruby PStore.abort用法及代碼示例
- Ruby PStore.[]=用法及代碼示例
- Ruby PrettyPrint.current_group用法及代碼示例
- Ruby Pathname.<=>用法及代碼示例
- Ruby Pathname.children用法及代碼示例
- Ruby Process.groups用法及代碼示例
- Ruby Process.wait2用法及代碼示例
- Ruby Process.getpgrp用法及代碼示例
- Ruby Proc.eql?用法及代碼示例
- Ruby PTY.open用法及代碼示例
- Ruby PrettyPrint.genspace用法及代碼示例
- Ruby PKey.sign_raw用法及代碼示例
- Ruby Profiler模塊用法及代碼示例
- Ruby Process.setproctitle用法及代碼示例
- Ruby PPMethods.comma_breakable用法及代碼示例
- Ruby Process.setrlimit用法及代碼示例
- Ruby Proc.prc ==用法及代碼示例
- Ruby Profiler.raw_data用法及代碼示例
- Ruby Process.uid用法及代碼示例
- Ruby Pathname.descend用法及代碼示例
- Ruby Process.pid用法及代碼示例
- Ruby Proc.ruby2_keywords用法及代碼示例
- Ruby Pathname.getwd用法及代碼示例
- Ruby PKey.generate_parameters用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 PStore類。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。