class Gash::Tree
A Tree
is a Hash which can store other instances of Tree
and Blob
.
Special methods¶ ↑
Internally, a tree is being stored like this:
{ "README" => blob, "examples" => { "test.rb" => blob, "yay.rb" => blob } }
So you have to do tree["examples"].delete("test.rb")
instead of tree.delete("examples/test.rb")
. However, there are some methods which supports the slash. All of these will work:
tree["examples/test.rb"] tree.fetch("examples/test.rb") tree["examples/another.rb"] = "Content" tree.store("examples/another.rb", "Content") # Exactly the same as above. tree["examples"]["test.rb"] # Or, you could use this
Documentation¶ ↑
The point of Tree
is that it should be as close to Hash as possible. Therefore, methods which behaves exactly equally in Gash
and Hash will not be documentated below. Please see the Ruby documentation if you wonder what you can do.
Public Instance Methods
Retrieves the value stored as key
:
tree["FILE"] == File.read("FILE") tree["DIR/FILE"] == tree["DIR"]["FILE"] == File.read("DIR/FILE")
Lazy loading¶ ↑
By default, this method will automatically load the blob/tree from the repo. If you rather want to load it later, simply set lazy
to true
:
blob = tree["FILE", true] # do some other stuff... blob.load! # Load it now!
# File lib/gash.rb, line 171 def [](key, lazy = nil) ret = fetch(key, default) ensure ret.load! if ret.respond_to?(:load!) && !lazy end
Stores the given value at key
:
tree["FILE"] = "Content"
It uses Helpers#normalize
in order convert it to a blob/tree, and will always set the parent to itself:
tree["FILE"] = "Content" # is the same as: tree["FILE"] = Gash::Blob.new(:content => "Content", :parent => tree)
Mark as changed¶ ↑
By default, the object will be marked as changed (using Helpers#changed!
). If this is not what you want, simply set not_changed
to true
.
However, if you give it three arguments, then the second one will act as not_changed
, not the third:
1 2 3 tree["FILE", true] = "Test" tree["FILE"].changed? # => false
# File lib/gash.rb, line 201 def []=(key, value, not_changed = nil) key, value, not_changed = if not_changed.nil? [key, value] else [key, not_changed, value] end if key.include?("/") keys = key.split("/") name = keys.pop keys.inject(self) do |memo, i| memo[i, not_changed] = Tree.new(:parent => self) unless memo.include?(i) memo[i, true] end[name, not_changed] = value else value = normalize(value) value.parent = self super(key, value) end ensure self.changed! unless not_changed end
Converts the tree to a Hash.
# File lib/gash.rb, line 226 def to_hash inject({}) do |memo, (key, value)| memo[key] = value.respond_to?(:to_hash) ? value.to_hash : value.to_s memo end end