Skip to content

Commit

Permalink
Fix bug constructorTagTransform (#41)
Browse files Browse the repository at this point in the history
* Add failing test for constructorTagTransform

* Fix bug with some constructoTagTransform functions
  • Loading branch information
abaco authored and paf31 committed Feb 16, 2018
1 parent 9ff97e6 commit e35698c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Data/Foreign/Generic/Class.purs
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ instance genericDecodeConstructor
then Constructor <$> readArguments f
else case opts.sumEncoding of
TaggedObject { tagFieldName, contentsFieldName, constructorTagTransform } -> do
tag <- mapExcept (lmap (map (ErrorAtProperty contentsFieldName))) do
tag <- mapExcept (lmap (map (ErrorAtProperty tagFieldName))) do
tag <- index f tagFieldName >>= readString
let expected = constructorTagTransform ctorName
unless (constructorTagTransform tag == expected) $
unless (tag == expected) $
fail (ForeignError ("Expected " <> show expected <> " tag"))
pure tag
args <- mapExcept (lmap (map (ErrorAtProperty contentsFieldName)))
Expand Down
16 changes: 14 additions & 2 deletions test/Types.purs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Data.Foreign (ForeignError(ForeignError), fail, readArray, toForeign)
import Data.Foreign.Class (class Encode, class Decode, encode, decode)
import Data.Foreign.Generic (defaultOptions, genericDecode, genericEncode)
import Data.Foreign.Generic.EnumEncoding (defaultGenericEnumOptions, genericDecodeEnum, genericEncodeEnum)
import Data.Foreign.Generic.Types (Options, SumEncoding(..))
import Data.Foreign.NullOrUndefined (NullOrUndefined)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Eq (genericEq)
Expand Down Expand Up @@ -67,11 +68,22 @@ instance showIntList :: Show IntList where
instance eqIntList :: Eq IntList where
eq x y = genericEq x y

intListOptions :: Options
intListOptions =
defaultOptions { unwrapSingleConstructors = true
, sumEncoding = TaggedObject { tagFieldName: "tag"
, contentsFieldName: "contents"
, constructorTagTransform: \tag -> case tag of
"Cons" -> "cOnS"
_ -> ""
}
}

instance decodeIntList :: Decode IntList where
decode x = genericDecode (defaultOptions { unwrapSingleConstructors = true }) x
decode x = genericDecode intListOptions x

instance encodeIntList :: Encode IntList where
encode x = genericEncode (defaultOptions { unwrapSingleConstructors = true }) x
encode x = genericEncode intListOptions x

-- | Balanced binary leaf trees
data Tree a = Leaf a | Branch (Tree (TupleArray a a))
Expand Down

0 comments on commit e35698c

Please sign in to comment.