Module: Yargi::Markable
- Included in:
- Digraph, Digraph::Edge, Digraph::Vertex
- Defined in:
- lib/yargi/markable.rb
Overview
Allows users to put its own marks on graph elements. A Hash-like API for setting and getting these marks is provided through []
and []=
. When a Symbol object is used as a mark key (and provided it does’nt lead to a name collision), accessors are automatically defined as singleton methods (without creating an instance variable however).
Instance Method Summary collapse
-
#add_marks(marks = nil) ⇒ Object
(also: #merge_marks)
Add all marks provided by a Hash instance marks.
-
#get_mark(key) ⇒ Object
(also: #[])
Returns the mark value installed under key.
-
#has_mark?(key) ⇒ Boolean
Checks if a given mark exists.
-
#set_mark(key, value) ⇒ Object
(also: #[]=)
Sets a key/value pair as a mark.
-
#tag(*modules) ⇒ Object
Tag this element with some modules.
-
#to_h(nonil = true) ⇒ Object
Converts this Markable to a Hash.
Instance Method Details
#add_marks(marks = nil) ⇒ Object Also known as: merge_marks
Add all marks provided by a Hash instance marks.
46 47 48 49 50 51 52 |
# File 'lib/yargi/markable.rb', line 46 def add_marks(marks=nil) marks.each_pair {|k,v| self[k]=v} if marks if block_given? result = yield self add_marks(result) if Hash===result end end |
#get_mark(key) ⇒ Object Also known as: []
Returns the mark value installed under key. Returns nil if no such mark.
23 24 25 |
# File 'lib/yargi/markable.rb', line 23 def get_mark(key) @marks ? @marks[key] : nil; end |
#has_mark?(key) ⇒ Boolean
Checks if a given mark exists
18 19 20 |
# File 'lib/yargi/markable.rb', line 18 def has_mark?(key) @marks and @marks.has_key?(key) end |
#set_mark(key, value) ⇒ Object Also known as: []=
Sets a key/value pair as a mark. Overrides previous mark value if key is already in used. Automatically creates accessors if key is a Symbol and such methods do not already exists.
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/yargi/markable.rb', line 31 def set_mark(key, value) @marks = {} unless @marks @marks[key] = value if Symbol===key and not(self.respond_to?(key) or self.respond_to?("#{key}=".to_sym)) instance_eval %Q{ class << self def #{key}() @marks[:#{key}]; end def #{key}=(value) @marks[:#{key}]=value; end end } end end |
#tag(*modules) ⇒ Object
Tag this element with some modules
13 14 15 |
# File 'lib/yargi/markable.rb', line 13 def tag(*modules) modules.each {|mod| self.extend(mod)} end |
#to_h(nonil = true) ⇒ Object
Converts this Markable to a Hash. When nonil is true, nil mark values do not lead to hash entries.
57 58 59 60 61 62 63 64 |
# File 'lib/yargi/markable.rb', line 57 def to_h(nonil=true) return {} unless @marks marks = @marks.dup if nonil marks.delete_if {|k,v| v.nil?} end marks end |