haskell-hvr / cassava

A CSV parsing and encoding library optimized for ease of use and high performance
http://hackage.haskell.org/package/cassava
BSD 3-Clause "New" or "Revised" License
223 stars 107 forks source link

ToNamedRecord defaultFieldLabelModifier #170

Closed dmjio closed 5 years ago

dmjio commented 5 years ago

I seem to be unable to strip the prefix of a record before serializing it to a ByteString for cassava-0.5.1.0.

Expected:

Lol,Bob
a,b

Actual:

-- *** Exception: Data.Csv.Encoding.namedRecordToRecord: header contains name "fooLol" which is not present in the named record
-- CallStack (from HasCallStack):
--   error, called at ./Data/Csv/Encoding.hs:312:24 in cassava-0.5.1.0-7OIAGgXyTgOKDbnfTKfKkh:Data.Csv.Encoding

Minimal example:

{-# LANGUAGE DeriveGeneric #-}
module Main where

import Data.ByteString.Lazy.Char8 as B8
import Data.Csv
import GHC.Generics

main :: IO ()
main = B8.putStrLn $ encodeDefaultOrderedByName [ Foo "a" "b" ]

data Foo
  = Foo
  { fooLol :: String
  , fooBob :: String
  } deriving (Show, Eq, Generic)

instance DefaultOrdered Foo

instance ToNamedRecord Foo where
  toNamedRecord = genericToNamedRecord defaultOptions
    { fieldLabelModifier = Prelude.drop (Prelude.length ("foo" :: String))
    }
dmjio commented 5 years ago

Ah whoops, I forgot to add it for both DefaultOrdered and ToNamedRecord

instance DefaultOrdered Foo where                                                                                                                                                                              
  headerOrder = genericHeaderOrder defaultOptions                                                                                                                                                              
    { fieldLabelModifier = Prelude.drop (Prelude.length ("foo" :: String))                                                                                                                                     
    }