Module: Fend::Plugins::DataProcessing
- Defined in:
- lib/fend/plugins/data_processing.rb
Overview
By default, Fend provides methods for input and output processing.
class UserValidation < Fend
#...
def process_input(input)
# symbolize input data keys
symbolized_input = input.each_with_object({}) do |(key, value), result|
new_key = key.is_a?(String) ? key.to_sym : key
result[new_key] = value
end
# do some additional processing
end
def process_output(output)
# filter output data
whitelist = [:username, :email, :address]
filtered_output = output.each_with_object({}) do |(key, value), result|
result[key] = value if whitelist.include?(key)
end
# do some additional processing
end
end
‘data_processing` plugin allows you to define processing steps in more
declarative manner:
plugin :data_processing
process(:input) do |input|
# symbolize keys
end
process(:output) do |output|
# filter
end
You can define as much processing steps as you need and they will be executed in order in which they are defined.
## Built-in processings
You can activate built-in processings when loading the plugin:
# this will:
# symbolize and freeze input data
# stringify output data
plugin :data_processing, input: [:symbolize, :freeze],
output: [:stringify]
:symbolize : Symbolizes keys.
:stringify : Stringifies keys
:dup : Duplicates data
:freeze : Freezes data
All of the above support deeply nested data.
Built-in processings are executed before any user-defined ones.
## Data mutation
Fend will never mutate the raw input data you provide:
raw_input = { username: "john", email: "john@example.com" }
UserValidation.call(raw_input)
However, nothing can stop you from performing destructive operations (‘merge!`, `delete`, etc…) in custom processing steps. If you intend to mutate input/output data, make sure to use `:dup` processing, in order to ensure immutability.
Defined Under Namespace
Modules: ClassMethods, InstanceMethods Classes: Process
Constant Summary collapse
- BUILT_IN_PROCESSINGS =
{ symbolize: ->(data) { Process.symbolize_keys(data) }, stringify: ->(data) { Process.stringify_keys(data) }, dup: ->(data) { Process.duplicate(data) }, freeze: ->(data) { Process.frost(data) } }.freeze
Class Method Summary collapse
Class Method Details
permalink .configure(validation, options = {}) ⇒ Object
[View source]
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/fend/plugins/data_processing.rb', line 93 def self.configure(validation, = {}) validation.opts[:data_processing] = {} validation.opts[:data_processing][:input] ||= [] validation.opts[:data_processing][:output] ||= [] return if .empty? .each do |data_ref, processings| processings.each_with_object(validation.opts[:data_processing][data_ref]) do |name, result| raise Error, "Built-in processing not found: ':#{name}'" unless BUILT_IN_PROCESSINGS.key?(name) result << BUILT_IN_PROCESSINGS[name] end end end |