ruby-hl7 - creating a new segment class

Ok, so you want to do something more than muck with some fields in passing segments. Ruby-hl7 provides a nice way to encapsulate specific segments as objects, dealing with field aliases instead of field id numbers. After all isn’t my_obj.last_checkup_date a little clearer than my_obj.e11. I certainly think so, which is why you can define a class for a segment type. Let’s create a class describing a BLG (Billing) segment.

# When a message is parsed, the parser checks for a class matching this format
class HL7::Message::Segment::BLG < HL7::Message::Segment
  weight 600  # we want this to go after every other segment (they are sorted ascendingly)

  # we're adding a field alias to BLG.1, which happens to be "when to charge" in the docs
  add_field :name=>:when_to_charge 
  # we'll include some value checking logic in the next field we add
  add_field :name=>:charge_type do |c|
     raise"Invalid charge type") unless c
     raise"Invalid charge type") unless VALID_CHARGES.index(c)
     c # we need to return the final value of c as this is called on read/write

  # we can explicitly set the field id, this would point to BLG.4
  add_field :name=>:charge_type_reason, :idx=>4

Now let’s use it:

# create the empty hl7 message
msg =

# create our segments and fill in some data
msh = 
blg =
blg.when_to_charge =
blg.charge_type = "CH"

msg << msh
msg << blg

There you go, the suggested method for dealing with known segments.