From 1605b43a4dc5df60a5dcb6ddd98fd1b595e0375c Mon Sep 17 00:00:00 2001 From: Alessandro Desantis Date: Sat, 26 Dec 2015 10:11:20 +0300 Subject: [PATCH 1/2] Allow filtering subregions by type --- README.md | 5 +++++ lib/carmen/region_collection.rb | 11 +++++++++++ spec/carmen/region_collection_spec.rb | 16 ++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 spec/carmen/region_collection_spec.rb diff --git a/README.md b/README.md index 9dafef46..356c8ebc 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,11 @@ similarly to a `Country` to find, for instance, a specific state: illinois = us.subregions.coded('IL') => <#Carmen::Region "Illinois"> +You can also find all subregions with a specific type: + + states = us.subregions.typed('state') + => [<#Carmen::Region name="Alaska" type="state">, <#Carmen::Region name="Alabama" type="state">, ...] + Subregions support a smaller set of attributes than countries: illinois.name diff --git a/lib/carmen/region_collection.rb b/lib/carmen/region_collection.rb index af2228b8..74a1f16d 100644 --- a/lib/carmen/region_collection.rb +++ b/lib/carmen/region_collection.rb @@ -16,6 +16,17 @@ module Carmen class RegionCollection < Array include Querying + # Filters the regions in this collection by type. + # + # type - The String type to filter by + # + # Returns a region collection containing all the regions with the supplied + # type. + def typed(type) + results = select{ |r| r.type.downcase == type.downcase } + Carmen::RegionCollection.new(results) + end + private def query_collection diff --git a/spec/carmen/region_collection_spec.rb b/spec/carmen/region_collection_spec.rb new file mode 100644 index 00000000..04662bfa --- /dev/null +++ b/spec/carmen/region_collection_spec.rb @@ -0,0 +1,16 @@ +require 'spec_helper' + +describe Carmen::RegionCollection do + + before do + @collection = Carmen::RegionCollection.new([ + Carmen::Region.new('type' => 'custom_type1', 'code' => 'AA'), + Carmen::Region.new('type' => 'custom_type2', 'code' => 'BB') + ]) + end + + it 'provides an API for filtering regions by type' do + @collection.typed('custom_type1').map(&:code).must_equal ['AA'] + end + +end From b9a43cd4a873fa611a5eddcbd5d5f50cca6cf6ef Mon Sep 17 00:00:00 2001 From: Alessandro Desantis Date: Sun, 10 Jan 2016 17:51:46 +0300 Subject: [PATCH 2/2] Improve performance --- lib/carmen/region_collection.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/carmen/region_collection.rb b/lib/carmen/region_collection.rb index 74a1f16d..1db8e76b 100644 --- a/lib/carmen/region_collection.rb +++ b/lib/carmen/region_collection.rb @@ -23,7 +23,8 @@ class RegionCollection < Array # Returns a region collection containing all the regions with the supplied # type. def typed(type) - results = select{ |r| r.type.downcase == type.downcase } + downcased_type = type.downcase + results = select{ |r| r.type == downcased_type } Carmen::RegionCollection.new(results) end