Method: RSQL::EvalContext#grep

Defined in:
lib/rsql/eval_context.rb

#grep(pattern, *gopts) ⇒ Object (private)

Remove all rows that do NOT match the expression. Returns true if any matches were found.

Options:

:fixed   => indicates that the string should be escaped of any
            special characters
:nocolor => will not add color escape codes to indicate the
            match
:inverse => reverses the regular expression match


526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/rsql/eval_context.rb', line 526

def grep(pattern, *gopts) # :doc:
    nocolor = gopts.include?(:nocolor)

    if inverted = gopts.include?(:inverse)
        # there's no point in coloring matches we are removing
        nocolor = true
    end

    if gopts.include?(:fixed)
        regexp = Regexp.new(/#{Regexp.escape(pattern.to_str)}/)
    elsif Regexp === pattern
        regexp = pattern
    else
        regexp = Regexp.new(/#{pattern.to_str}/)
    end

    rval = inverted

    @results.delete_if do |row|
        matched = false
        row.each do |val|
            val = val.to_s unless String === val
            if nocolor
                if matched = !val.match(regexp).nil?
                    rval = inverted ? false : true
                    break
                end
            else
                # in the color case, we want to colorize all hits in
                # all columns, so we can't early terminate our
                # search
                if val.gsub!(regexp){|m| "\e[31;1m#{m}\e[0m"}
                    matched = true
                    rval = inverted ? false : true
                end
            end
        end
        inverted ? matched : !matched
    end

    return rval
end