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.1'.freeze
@@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.



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

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

Class Attribute Details

.default_languageObject

Returns the value of attribute default_language.



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

def default_language
  @default_language
end

Instance Attribute Details

#languageObject (readonly)

Returns the value of attribute language.



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

def language
  @language
end

Instance Method Details

#+(text) ⇒ Object



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

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

#<<(text) ⇒ Object



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

def <<(text)
  if text.is_a?(CodeString)
    if language == text.language
      super text
    else
      raise IncompatibleLanguage, "Language #{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] || '  '
  (strip.gsub(/^/, spacer * depth) + "\n").c(@language)
end

#inspectObject



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

def inspect
  to_s
end

#to_formatted_sObject



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

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