Sha256: 70221083022677790f5ca2e906a5eadfdf64c1922e0e6ff5f48c4b88b7c25fba

Contents?: true

Size: 1.86 KB

Versions: 10

Compression:

Stored size: 1.86 KB

Contents

module Deep
  KEYS = 0x01
  VALUES = 0x02

  #
  # deep mapping
  def self.map(o, mode, &block)
    case o
    when Hash
      o.inject({}) do |hash, (k,v)|
        k = yield(k) if (mode & KEYS) != 0
        v = map(v, mode, &block)
        hash.update k => v
        hash
      end
    when Array
      if mode & VALUES
        o.map do |v|
          map(v, mode, &block)
        end
      else
        o.dup
      end
    else
      if (mode & VALUES) != 0
        yield o 
      else
        o
      end
    end
  end

  #
  # deep reject
  def self.reject(o, mode, &block)
    case o
    when Hash
      o.inject({}) do |hash, (k,v)|
        next hash if (mode & KEYS) && yield(k)
        v = reject v, mode, &block
        next hash if (mode & VALUES) && yield(v)
        hash.update k => v
        hash
      end
    when Array
      if mode & VALUES
        o.inject([]) do |r, v|
          v = reject(v, mode, &block)
          r << v unless yield(v)
        end
      else
        o.dup
      end
    else
      o
    end
  end
end

module Enumerable
  KEYS = Deep::KEYS
  VALUES = Deep::VALUES

  def reject_blanks
    Deep.reject(self, KEYS | VALUES) do |s|
      s.blank?
    end
  end

  def camelize
    Deep.map(self, KEYS) do |s|
      s.to_s.camelize
    end
  end
end

module Deep::Etest
  def test_reject_blanks
    h = { :a => "a", :b_c => { :d => nil, :video_test => "video_test "}, "x" => nil, "y" => [] }
    expected = { :a=>"a", :b_c => { :video_test => "video_test " }}
    assert_equal(expected, h.reject_blanks)
  end

  def test_camelized_keys
    h = { :a => "a", :b_c => { :d => "dd", :video_test => "video_test "}}
    expected = { "A"=>"a", "BC" => { "VideoTest" => "video_test ", "D" => "dd" }}
    assert_equal(expected, h.camelize)
  end

  def test_missin_block
    assert_raise(LocalJumpError) {
      Deep.reject(%w(1 2), 3)
    }
  end
end if VEX_TEST == "base"

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
vex-0.4.2 lib/vex/base/enumerable/deep.rb
vex-0.3.3 lib/vex/base/enumerable/deep.rb
vex-0.2.9 lib/vex/base/enumerable/deep.rb
vex-0.2.8 lib/vex/base/enumerable/deep.rb
vex-0.2.7 lib/vex/base/enumerable/deep.rb
vex-0.2.6 lib/vex/base/enumerable/deep.rb
vex-0.2.5 lib/vex/base/enumerable/deep.rb
vex-0.2.2 lib/vex/base/enumerable/deep.rb
vex-0.2.1 lib/vex/base/enumerable/deep.rb
vex-0.2 lib/vex/base/enumerable/deep.rb