Class: HealthSeven::Message

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

Defined Under Namespace

Classes: Message, MessageDef, Segment, SegmentDef

Class Method Summary collapse

Class Method Details

.clean_tree(node, segment) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/health_seven/message.rb', line 219

def self.clean_tree(node, segment)
  if node.is_a?(Treetop::Runtime::SyntaxNode)  &&  !node.elements
    return false
  end

  segment.name = node.name
  segment.fields = node.fields
  @required_segments.delete(node.name.downcase)

  return true unless node.elements
  node.elements.each do |e|
    if e.is_a?(HealthSeven::SegmentLiteral)
      child_segment = Segment.new
      if self.clean_tree(e, child_segment)
        segment.children << child_segment
      end
    elsif e.elements
      e.elements.each do |ee|
        child_segment = Segment.new
        if self.clean_tree(ee, child_segment)
          segment.children << child_segment
        end
      end
    end
  end
end

.define_message(&block) ⇒ Object



134
135
136
137
# File 'lib/health_seven/message.rb', line 134

def self.define_message(&block)
  @message_def = MessageDef.new(:message, &block)
  self.load_grammar
end

.load_grammarObject



151
152
153
154
# File 'lib/health_seven/message.rb', line 151

def self.load_grammar
  Object.const_set("#{self.name}Grammar", Module.new)
  Treetop.load_from_string(treetop_grammar)
end

.message_defObject



139
140
141
# File 'lib/health_seven/message.rb', line 139

def self.message_def
  @message_def
end

.parse(data) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/health_seven/message.rb', line 196

def self.parse(data)
  parser = Object.const_get("#{self.name}GrammarParser").new
  # Pass the data over to the parser instance
  ast_tree = parser.parse(data)

  # If the AST is nil then there was an error during parsing
  # we need to report a simple error message to help the user
  if(ast_tree.nil?)
    message = ""
    parser.failure_reason =~ /^(Expected .+) after/m
    message << "#{$1.gsub("\n", '$NEWLINE')}:"
    message << data.lines.to_a[parser.failure_line - 1]
    message << "#{'~' * (parser.failure_column - 1)}^"
    raise HealthSeven::BadGrammarException, message
  end
  msg = Message.new
  @required_segments = Object.const_get("#{self.name}").message_def.required
  self.clean_tree(ast_tree, msg)
  raise "No required segment(s) found: #{@required_segments.join(', ')}" unless @required_segments.empty?

  msg
end

.treetop_grammarObject



143
144
145
146
147
148
149
# File 'lib/health_seven/message.rb', line 143

def self.treetop_grammar
  <<-RULE
  grammar  #{self.name}Grammar
  #{@message_def.to_gramar([]).join("\n")}
  end
  RULE
end