06 Validation and logging - kjellhex/diode GitHub Wiki
When building an application, you will quickly come across the need to validate user input, and the need to log various interesting events.
Diode is deliberately limited in scope, allowing the developer to handle all other facets in whatever way is deemed best. Diode does not prescribe or enforce any particular approach to addressing these requirements, but some auxillary gists are offered in case they are useful as a starting point.
Validation
It may be useful to create a set of validation routines to reduce the workload involved in building services. Quite a bit of effort needs to go into validating user input before it is put to use, so any way of making that succinct and easy should be considered.
An example gist - valid.rb is offered to demonstrate one way of approaching the challenge of validating user input. Feel free to take it and modify it for your needs, or else ignore it as you see fit.
Here are some examples of what it can do for you. Each of these statements does nothing if the data is valid, or raises a RuntimeError id the data is invalid:
Valid.input(s, :digits, 6) ensures the string contains only digits and is not longer than 6 digits
Valid.input(s, :digits, 7..9) ensures the string has a length of 7,8 or 9 digits only
Valid.input(s, :digits, 6..6) ensures the string has a length of exactly 6 digits only
Valid.input(s, :text, 35) ensures the string is less than 36 chars long (any chars allowed)
Valid.input(s, :alpha, 12) ensures the string is less than 12 chars long and contains only letters (a..zA..Z)
Valid.input(s, "1234567890,.$-", 5..8) allows a formatted dollar amount using custom charset
Valid.input(s, :date) checks for exactly 8 digits that make a valid date
Logging
There is a standard logger provided by Ruby and there are gems, or you can create your own.
An example gist - logging.rb is offered to demonstrate one approach to logging. The key difference here is that each call to the logger opens the file for appending and closes the file afterwards. This appears to be extremely fast on modern file systems. The major benefits are that it:
- behaves well when log rotation is handled externally to the application (eg. by logrotate or a cron job)
- allows threads to log to the same file without fuss
- specifies the log filename directly so there is no extra work to open a file, check its ok, handle problems if its not, etc.
- when $DEBUG is true, the logger also echoes to the STDOUT terminal for convenience during development and testing
- allows you to control the log message format directly
Some logging frameworks want to be generic all-things-to-all-people so they are complex. An alternative is to take a gist like this and incorporate a modified version in each application. Feel free to take the approach that suits you best.