Last active
July 9, 2017 16:48
-
-
Save alexandru-calinoiu/984ab8e61546f7bb26b3266bc2b6aec8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#inspired by http://blog.martinosis.com/blog/simple-functional-strong-params-in-ruby/ | |
require 'pp' | |
filter_hash = -> keys, params { | |
keys.map { |key| [key, params[key]] }.to_h | |
}.curry | |
params = { name: 'Ion', age: 42, pwd: 'plain', contact: { address: 'Danil Ionescu' } } | |
pp filter_hash.([:name, :age]).(params) | |
hash_of = -> (fields, hash) { | |
hash ||= {} | |
fields.map { |key, fn| [key, fn.(hash[key])] }.to_h | |
}.curry | |
same = -> a { a } | |
contact = hash_of.(address: same) | |
user = hash_of.(name: same, | |
age: same, | |
contact: contact) | |
pp user.(params) | |
array_of = -> fn, value { value.kind_of?(Array) ? value.map(&fn) : [] }.curry | |
contact_params = [{ address: '21 Jump Street', remove: 'me' }, { address: '24 Sussex', remove: 'me too' }, { address: '' }] | |
pp array_of.(contact).(contact_params) | |
default = -> default, a { a.empty? ? default : a }.curry | |
contact = hash_of.(address: default.('N/A')) | |
pp array_of.(contact).(contact_params) | |
scalar = -> a { a.kind_of?(Array) || a.kind_of?(Hash) ? nil : a } | |
pp hash_of.(name: scalar).(name: { hack: 'something' }) | |
pp hash_of.(name: scalar).(name: 'Ion') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment