Class: Parser

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Parser

Returns a new instance of Parser.



3
4
5
6
7
8
9
# File 'lib/parser.rb', line 3

def initialize(hash)
  @string  = hash[:string]
  @keyword = hash[:keyword]
  raise "No Keyword given" unless keyword
  raise "Nothing to parse given" unless string
  raise "No #{keyword} given." unless /#{keyword}(.*)/.match(string)
end

Instance Attribute Details

#createObject (readonly)

Returns the value of attribute create.



2
3
4
# File 'lib/parser.rb', line 2

def create
  @create
end

#keywordObject (readonly)

Returns the value of attribute keyword.



2
3
4
# File 'lib/parser.rb', line 2

def keyword
  @keyword
end

#parsingObject (readonly)

Returns the value of attribute parsing.



2
3
4
# File 'lib/parser.rb', line 2

def parsing
  @parsing
end

#stringObject (readonly)

Returns the value of attribute string.



2
3
4
# File 'lib/parser.rb', line 2

def string
  @string
end

Class Method Details

.title_and_body_by_keyword_from_string(hash) ⇒ Object



11
12
13
14
15
16
17
18
19
20
# File 'lib/parser.rb', line 11

def self.title_and_body_by_keyword_from_string(hash)
  parser = self.new(hash)
  titles = parser.parse_titles
  bodies = parser.parse_bodies
  arr = []
  titles.each_with_index do |t,i|
    arr << {:title => t, :body => bodies[i]}
  end
  arr
end

Instance Method Details

#parse_bodiesObject



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/parser.rb', line 26

def parse_bodies
  bodies = string.split(/(^|\s+)(#{keyword}.*)/).reject {|s| s.empty? }.reject {|s| s.only_whitespace? }.map {|s| s.strip}
  start = 0
  bodies.each_with_index do |o,i| 
    if (o =~ /^\s*#{keyword}.*\s*$/)
      start = i
      break
    end
  end
  bodies[start..bodies.length].select {|s| !(s =~ /^\s*#{keyword}.*\s*$/) }
end

#parse_titlesObject



22
23
24
# File 'lib/parser.rb', line 22

def parse_titles
  string.scan(/(^|\s+)#{keyword}(.*)/).map {|a| a[1].strip}
end