Class: CodeString

Inherits:
String show all
Defined in:
lib/code_string.rb

Overview

CodeString is string with an indicator of the manipulated language It permits to secure concantenation Code strings simplifies code displaying

Defined Under Namespace

Classes: IncompatibleLanguage

Constant Summary collapse

VERSION =
"0.0.0"
@@default_language =
:ruby

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from String

#c, #to_code

Constructor Details

#initialize(text, language = nil) ⇒ CodeString

Returns a new instance of CodeString.



19
20
21
22
# File 'lib/code_string.rb', line 19

def initialize(text, language = nil)
  @language = language || @@default_language
  super(text)
end

Class Attribute Details

.default_languageObject

Returns the value of attribute default_language.



14
15
16
# File 'lib/code_string.rb', line 14

def default_language
  @default_language
end

Instance Attribute Details

#languageObject (readonly)

Returns the value of attribute language.



17
18
19
# File 'lib/code_string.rb', line 17

def language
  @language
end

Instance Method Details

#+(text) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/code_string.rb', line 24

def +(text)
  if text.is_a?(CodeString)
    if self.language == text.language
      super text
    else
      raise IncompatibleLanguage, "Language #{self.language} is not compatible with language: #{text.language}"
    end
  else
    super text
  end
end

#<<(text) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/code_string.rb', line 36

def <<(text)
  if text.is_a?(CodeString)
    if self.language == text.language
      super text
    else
      raise IncompatibleLanguage, "Language #{self.language} is not compatible with language: #{text.language}"
    end
  else
    super text.to_s
  end
end

#dig(*args) ⇒ Object



63
64
65
66
67
68
# File 'lib/code_string.rb', line 63

def dig(*args)
  options = args.last.is_a?(Hash) ? args.delete_at(-1) : {}
  depth   = args.shift || options[:depth] || 1
  spacer  = args.shift || options[:spacer] || "  "
  return (self.strip.gsub(/^/, spacer * depth) + "\n").c(@language)
end

#inspectObject



59
60
61
# File 'lib/code_string.rb', line 59

def inspect
  self.to_s
end

#to_formatted_sObject



48
49
50
51
52
53
54
55
56
57
# File 'lib/code_string.rb', line 48

def to_formatted_s
  string, index = "", 1
  string << "# language: #{language}\n"
  string << "# encoding: #{encoding}\n"
  for line in self.split(/\n/)
    string  << index.to_s.rjust(4) + ": " + line + "\n"
    index += 1
  end
  return string
end