Sha256: 68c90f818ee2b71af4eee4e6366ddd40e506f4487a36d003e3b32a7b85d10d3d

Contents?: true

Size: 1.91 KB

Versions: 5

Compression:

Stored size: 1.91 KB

Contents

require 'transproc/support/deprecations'

module Transproc
  # Transproc helper that adds `t` method as a shortcut for `Transproc` method
  #
  # @example
  #   include Transproc::Helper
  #
  #   t(:to_string)
  #
  # @api public
  module Helper
    # @api private
    def self.included(*)
      Transproc::Deprecations.announce(
        'Transproc::Helper',
        'Define your own function registry using Transproc::Registry extension'
      )
      super
    end

    # @see Transproc
    #
    # @api public
    def t(*args, &block)
      Transproc(*args, &block)
    end
  end

  # Helper extension handy for composing many functions in multiple steps
  #
  # @example
  #   include Transproc::Composer
  #
  #   fn = compose do |fns|
  #     fns << t(:map_array, t(:symbolize_keys))
  #     fns << t(:map_array, t(:nest, :address, [:city, :zipcode]))
  #   end
  #
  #   fn.call [{ 'city' => 'NYC', 'zipcode' => '123' }]
  #   # => [{ address: { city: 'NYC', zipcode: '123' }]
  #
  # @api public
  module Composer
    # @api private
    class Factory
      attr_reader :fns, :default

      # @api private
      def initialize(default = nil)
        @fns = []
        @default = default
      end

      # @api private
      def <<(other)
        fns.concat(Array(other).compact)
        self
      end

      # @api private
      def to_fn
        fns.reduce(:+) || default
      end

      # @deprecated
      # @api public
      def t(*args, &block)
        Transproc(*args, &block)
      end
    end

    # Gather and compose functions and fall-back to a default one if provided
    #
    # @example
    #   include Transproc::Composer
    #
    #   fn = compose(-> v { v }) do |fns|
    #     fns << t(:to_string) if something
    #   end
    #
    #   fn[1] # => "1"
    #
    # @see Composer
    #
    # @api public
    def compose(default = nil)
      factory = Factory.new(default)
      yield(factory)
      factory.to_fn
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
transproc-0.4.2 lib/transproc/composer.rb
transproc-0.4.1 lib/transproc/composer.rb
transproc-0.4.0 lib/transproc/composer.rb
transproc-0.3.2 lib/transproc/composer.rb
transproc-0.3.1 lib/transproc/composer.rb