Class: ContentSpinning

Inherits:
Object
  • Object
show all
Defined in:
lib/content_spinning.rb,
lib/content_spinning/string.rb,
lib/content_spinning/spinner.rb,
lib/content_spinning/version.rb,
lib/content_spinning/sentence.rb

Defined Under Namespace

Modules: Version Classes: Sentence, Spinner, String

Constant Summary collapse

SPIN_END =
"}"
SPIN_OR =
"|"
SPIN_START =
"{"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ ContentSpinning

Returns a new instance of ContentSpinning.



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

def initialize(source)
  @source = source
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



21
22
23
# File 'lib/content_spinning.rb', line 21

def source
  @source
end

Class Method Details

.spin(source, limit: nil) ⇒ Object



11
12
13
# File 'lib/content_spinning.rb', line 11

def spin(source, limit: nil)
  new(source).spin(limit: limit)
end

Instance Method Details

#countObject



23
24
25
# File 'lib/content_spinning.rb', line 23

def count
  parse.count
end

#parseObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/content_spinning.rb', line 31

def parse
  return @root if defined?(@root)

  heap = [::ContentSpinning::Sentence.new]

  source.scan(/ [{}|] | [^{}|]+ /x).each do |part|
    case part
    when SPIN_START
      modify_heap_for_spin_start(heap)
    when SPIN_OR
      modify_heap_for_spin_or(heap)
    when SPIN_END
      modify_heap_for_spin_end(heap)
    else
      heap.last << ::ContentSpinning::String.new(part)
    end
  end

  @root = heap.first.cleaned
end

#spin(limit: nil) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/content_spinning.rb', line 52

def spin(limit: nil)
  if limit && limit < count
    spin_with_limit(limit: limit)
  else
    spin_all
  end
end

#spin_allObject



60
61
62
# File 'lib/content_spinning.rb', line 60

def spin_all
  parse.spin
end

#spin_with_limit(limit:) ⇒ Object



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

def spin_with_limit(limit:)
  parsed = parse

  Array.new(limit) { parsed.random }
end

#to_sourceObject



70
71
72
# File 'lib/content_spinning.rb', line 70

def to_source
  parse.to_source
end