# 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

# we'll include some value checking logic in the next field we add
VALID_CHARGES = %w[ CH CO DR DP GR NC NP RS ]
raise HL7::Exception.new("Invalid charge type") unless c
raise HL7::Exception.new("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
end

# we can explicitly set the field id, this would point to BLG.4
end


Now let’s use it:

# create the empty hl7 message
msg = HL7::Message.new

# create our segments and fill in some data
msh = HL7::Message::Segment::MSH.new
blg = HL7::Message::Segment::BLG.new
blg.when_to_charge = Date.new.to_s
blg.charge_type = "CH"

msg << msh
msg << blg


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