Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7501: select_with_regex.patch

File select_with_regex.patch, 3.0 kB (added by nicwilliams, 1 year ago)

Select with regex - Code and tests

  • lib/active_support/core_ext.rb

    old new  
  • lib/active_support/core_ext/array.rb

    old new  
    11require File.dirname(__FILE__) + '/array/conversions' 
    22require File.dirname(__FILE__) + '/array/grouping' 
     3require File.dirname(__FILE__) + '/array/selections' 
    34 
    45class Array #:nodoc: 
    56  include ActiveSupport::CoreExtensions::Array::Conversions 
    67  include ActiveSupport::CoreExtensions::Array::Grouping 
     8  include ActiveSupport::CoreExtensions::Array::Selections 
    79end 
  • lib/active_support/core_ext/array/selections.rb

    old new  
     1module ActiveSupport #:nodoc: 
     2  module CoreExtensions #:nodoc: 
     3    module Array #:nodoc: 
     4      module Selections 
     5         
     6        def select_with_regex(regex=nil, &block) 
     7          if regex.is_a? Regexp 
     8            block = Proc.new  {|word| word =~ regex} 
     9          end 
     10          self.send :select_without_regex, &block 
     11        end 
     12         
     13        def self.included(base) 
     14          base.alias_method_chain :select, :regex 
     15        end 
     16      end 
     17    end 
     18  end 
     19end 
  • test/core_ext/array_ext_test.rb

    old new  
    180180    assert_equal 0, xml.rindex(/<\?xml /) 
    181181  end 
    182182end 
     183 
     184class ArrayExtSelectRegexTests < Test::Unit::TestCase 
     185  def test_select_with_regex_no_alias 
     186    assert_equal [], %w().select_with_regex(/foo/) 
     187    assert_equal(%w(foo too_foo_bar), %w(foo bar too_foo_bar fbar).select_with_regex(/foo/)) 
     188  end 
     189 
     190  def test_select_by_regex 
     191    assert_equal [], %w().select(/foo/) 
     192    assert_equal(%w(foo too_foo_bar), %w(foo bar too_foo_bar fbar).select(/foo/)) 
     193  end 
     194 
     195  def test_normal_select 
     196    assert_equal [], %w().select {|word| word =~ /foo/} 
     197    assert_equal(%w(foo too_foo_bar), %w(foo bar too_foo_bar fbar).select {|word| word =~ /foo/}) 
     198  end 
     199 
     200  def test_normal_select_without_regex 
     201    assert_equal [], %w().send(:select_without_regex, &proc {|word| word =~ /foo/}) 
     202    assert_equal %w(foo too_foo_bar), %w(foo bar too_foo_bar fbar).send(:select_without_regex, &proc {|word| word =~ /foo/}) 
     203  end 
     204end