Permalink
Browse files

Split Segment from SegmentUse to better match the schema

  • Loading branch information...
sorear committed Mar 14, 2013
1 parent 9030ae2 commit d6c56d3d836afd047c5a265ff1cdb773e1b02ec9
Showing with 33 additions and 18 deletions.
  1. +3 −18 lib/X12/Schema/Segment.pm
  2. +30 −0 lib/X12/Schema/SegmentUse.pm
View
@@ -3,9 +3,8 @@ package X12::Schema::Segment;
use Moose;
use namespace::autoclean;
-with 'X12::Schema::Sequencable';
-
has tag => (isa => 'Str', is => 'ro', required => 1);
+has friendly => (isa => 'Str', is => 'ro', required => 1);
has constraints => (isa => 'ArrayRef[X12::Schema::Constraint]', is => 'ro', default => sub { [] });
has elements => (isa => 'ArrayRef[X12::Schema::Element]', is => 'ro', required => 1);
has incomplete => (isa => 'Bool', is => 'ro', default => 0);
@@ -27,7 +26,7 @@ sub encode {
push @bits, $elem->encode($sink, $value);
} else {
if ($elem->required) {
- die "Segment ".$self->name." element ".$elem->name." is required";
+ die "Segment ".$self->friendly." element ".$elem->name." is required";
}
push @bits, '';
@@ -38,21 +37,7 @@ sub encode {
pop @bits while @bits && $bits[-1] eq '';
$sink->segment( join($sink->element_sep, $self->tag, @bits) . $sink->segment_term ) if @bits;
-}
-
-sub BUILD {
- my ($self) = @_;
-
- # DIVERSITY: possibly worth restricting use of 'B' type here?
-
- # This needs a little elaboration. Yes, we sometimes do not output a value.
- # But this flag only controls reading, and on read, entirely empty segments
- # should be suppressed. If a segment is required, it needs to have at least
- # one required element.
- $self->_can_be_empty(0);
-
- $self->_ambiguous_end_tags({});
- $self->_initial_tags({ $self->tag => 1 });
+ return @bits ? 1 : 0;
}
__PACKAGE__->meta->make_immutable;
@@ -0,0 +1,30 @@
+package X12::Schema::SegmentUse;
+
+use Moose;
+use namespace::autoclean;
+
+with 'X12::Schema::Sequencable';
+
+has def => (is => 'ro', isa => 'X12::Schema::Segment', required => 1);
+
+sub encode {
+ my ($self, $sink, $obj) = @_;
+
+ if (!$self->def->encode($sink, $obj) && $self->required) {
+ die 'Segment '.$self->name." must contain data\n";
+ }
+}
+
+sub BUILD {
+ my ($self) = @_;
+
+ # DIVERSITY: possibly worth restricting use of 'B' type here?
+
+ # we can only be empty in the event that we are optional, but in that case
+ # Sequence will automatically handle _can_be_empty and _ambiguous_end_tags.
+ $self->_can_be_empty(0);
+ $self->_ambiguous_end_tags({});
+ $self->_initial_tags({ $self->def->tag => 1 });
+}
+
+__PACKAGE__->meta->make_immutable;

0 comments on commit d6c56d3

Please sign in to comment.