Class: Symbol

Inherits:
Object
  • Object
show all
Defined in:
lib/impromptu/symbol.rb

Overview

Extensions to all Symbols to make it easier to deal with namespaced, nested symbol names

Instance Method Summary collapse

Instance Method Details

#base_symbolObject

Retrieve the base (end or final) symbol name from this symbol (the Class or Module actually being referred to).



24
25
26
# File 'lib/impromptu/symbol.rb', line 24

def base_symbol
  self.nested_symbols.last
end

#each_namespaced_symbolObject

Iterate through a namespaced symbol by visiting each name in turn, including its parent names. e.g calling on A::B::C would yield :A, :A::B, and :A::B::C



41
42
43
44
45
46
47
# File 'lib/impromptu/symbol.rb', line 41

def each_namespaced_symbol
  self.nested_symbols.inject([]) do |name, symbol|
    name << symbol
    yield name.join('::').to_sym
    name
  end
end

#nested?Boolean

True if this symbol contains namespaces (is a nested symbol such as A::B).

Returns:

  • (Boolean)


6
7
8
# File 'lib/impromptu/symbol.rb', line 6

def nested?
  self.without_leading_colons.include? '::'
end

#nested_symbolsObject

Split a symbol into its component names (A::B => [:A, :B])



18
19
20
# File 'lib/impromptu/symbol.rb', line 18

def nested_symbols
  self.without_leading_colons.split('::').collect(&:to_sym)
end

#root?Boolean

True if the symbol starts with two colons

Returns:

  • (Boolean)


34
35
36
# File 'lib/impromptu/symbol.rb', line 34

def root?
  self.to_s.start_with?('::')
end

#root_symbolObject

Retrieve the root (first) symbol name from this symbol.



29
30
31
# File 'lib/impromptu/symbol.rb', line 29

def root_symbol
  self.nested_symbols.first
end

#unnested?Boolean

True if this symbol contains no namespaces (is a root symbol such as A, in contrast to to A::B).

Returns:

  • (Boolean)


12
13
14
# File 'lib/impromptu/symbol.rb', line 12

def unnested?
  !self.nested?
end

#without_leading_colonsObject

Strip leading colons from a symbol name. Two leading colons indicate a symbol is relative to the root namespace (Object) but should be removed when determining nesting and nested symbols.



53
54
55
56
57
58
59
60
# File 'lib/impromptu/symbol.rb', line 53

def without_leading_colons
  str = self.to_s
  if str.start_with?('::')
    str[2..-1]
  else
    str
  end
end