Last active
December 14, 2015 07:29
-
-
Save 0xradical/5051450 to your computer and use it in GitHub Desktop.
Script to query phones
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PhoneQuery | |
def initialize(input) | |
@input = input | |
end | |
def to_sql | |
query = Phone.where('(1 = 0)').to_sql | |
return query if @input.blank? | |
@input = @input.strip.gsub(/[^0-9\s]/,'').split(/\s/) | |
if @input.size == 1 | |
number = @input.shift | |
if number.length <= 2 | |
query = Phone.where('LOWER(phones.area_code) LIKE :input OR LOWER(phones.number) LIKE :input',:input => "#{number}%").to_sql | |
else | |
query = Phone.where('LOWER(phones.number) LIKE :input', :input => "#{number}%").to_sql | |
end | |
else | |
area_code, number = @input.shift, @input.shift | |
query = Phone.where('LOWER(phones.area_code) LIKE ? AND LOWER(phones.number) LIKE ?',"#{area_code}%","#{number}%").to_sql | |
end | |
query | |
end | |
end | |
# rails runner phone_query.rb --test | |
if ARGV.shift == "--test" | |
require 'test/unit' | |
class PhoneQueryTest < Test::Unit::TestCase | |
def test_phone_query | |
assert_equal("SELECT `phones`.* FROM `phones` WHERE (LOWER(phones.area_code) LIKE '8%' OR LOWER(phones.number) LIKE '8%')", PhoneQuery.new('8').to_sql) | |
assert_equal("SELECT `phones`.* FROM `phones` WHERE (LOWER(phones.area_code) LIKE '81%' OR LOWER(phones.number) LIKE '81%')", PhoneQuery.new('81').to_sql) | |
assert_equal("SELECT `phones`.* FROM `phones` WHERE (LOWER(phones.number) LIKE '814%')", PhoneQuery.new('814').to_sql) | |
assert_equal("SELECT `phones`.* FROM `phones` WHERE (LOWER(phones.area_code) LIKE '12%' AND LOWER(phones.number) LIKE '81469797%')", PhoneQuery.new('12 8146-9797').to_sql) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment