These are chat archives for dry-rb/chat

7th
Sep 2018
Alexander
@cutalion
Sep 07 2018 17:07
Hey!
does anybody here use solnic's transproc?
I wonder how to map_value only if key exists in the input
Selection_390.png
Piotr Solnica
@solnic
Sep 07 2018 17:30
require 'transproc/all'

module T
  extend Transproc::Registry

  import Transproc::HashTransformations
  import Transproc::Conditional
end

class Transformer < Transproc::Transformer[T]
  guard(-> h { h.key?(:foo) }) do
    map_value(:foo, -> v { "#{v} was mapped" })
  end
end

t = Transformer.new

puts t.call({}).inspect
puts t.call({ foo: "bar" }).inspect
{}
{:foo=>"bar was mapped"}
@cutalion ^ this works
you can, of course, just add normal if inside the mapping function
Alexander
@cutalion
Sep 07 2018 17:31
yeah, I added custom function to my container
  def self.map_present_value(hash, key, fn)
    hash.key?(key) ? hash.merge(key => fn[hash[key]]) : hash
  end
thanks for the example of guard usage!
I tried it, but didn't get that I should pass a block to it

won't work. It will add a key with a nil value

you can, of course, just add normal if inside the mapping function

Piotr Solnica
@solnic
Sep 07 2018 17:36
ah I see
Alexander
@cutalion
Sep 07 2018 17:41

maybe you'll want to add a short function for my problem )
I'm transforming input values before updating record in the database.
I have an optional column rate_cents, but user works with the rate field (in dollars, not cents)

so, I do rename_keys :rate :rate_cents and than map_value :rate_cents, t(:to_cents) which does v.to_i * 100

so, rename key -> map value sequence
and I don't want this to add nil value for the field if user don't fill it
Piotr Solnica
@solnic
Sep 07 2018 17:45
yeah these are building blocks, it was the intention from the beginning that some conveniences will be added eventually