Last active
August 29, 2015 14:05
-
-
Save moxley/f1381321a0433d2a0bd0 to your computer and use it in GitHub Desktop.
In-memory Arel
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
| # require 'spec_helper' | |
| class InMemoryArel | |
| attr_accessor :collection | |
| def initialize(collection) | |
| self.collection = collection | |
| end | |
| def all | |
| collection | |
| end | |
| def where(conditions) | |
| _where(collection, conditions) | |
| end | |
| private | |
| def _where(working_collection, conditions) | |
| conditions.each do |key, value| | |
| working_collection = _where_key_matches(working_collection, key, value) | |
| break if working_collection.empty? | |
| end | |
| working_collection | |
| end | |
| def _where_key_matches(working_collection, key, value) | |
| working_collection.select do |e| | |
| e.public_send(key) == value | |
| end | |
| end | |
| end | |
| describe InMemoryArel do | |
| MySpecialClass = Struct.new(:id, :name, :category, :color) | |
| let(:collection) do | |
| [ | |
| {id: 1, name: "Apple", category: "fruit", color: "red"}, | |
| {id: 2, name: "Banana", category: "fruit", color: "yellow"}, | |
| {id: 3, name: "Pear", category: "fruit", color: "green"}, | |
| {id: 4, name: "Grape", category: "fruit", color: "green"}, | |
| {id: 5, name: "Orange", category: "fruit", color: "orange"}, | |
| {id: 6, name: "Pineapple", category: "fruit", color: "yellow"}, | |
| {id: 7, name: "Broccoli", category: "vegetable", color: "green"}, | |
| {id: 8, name: "Carrot", category: "vegetable", color: "orange"}, | |
| {id: 9, name: "Green Beans", category: "vegetable", color: "green"}, | |
| {id: 10, name: "Kale", category: "vegetable", color: "green"}, | |
| {id: 11, name: "Peas", category: "vegetable", color: "green"}, | |
| {id: 12, name: "Mac", category: "computer", color: "silver"}, | |
| {id: 13, name: "PC", category: "computer", color: "beige"}, | |
| ].map do |h| | |
| MySpecialClass.new(h[:id], h[:name], h[:category], h[:color]) | |
| end | |
| end | |
| subject(:arel) { InMemoryArel.new(collection) } | |
| describe "#all" do | |
| it "returns the collection" do | |
| expect(arel.all).to eq collection | |
| end | |
| end | |
| describe "#where" do | |
| it "returns elements that match the given key" do | |
| expect(arel.where(category: "computer").map(&:name)).to eq %w(Mac PC) | |
| end | |
| it "reduces results based on additional conditions" do | |
| expect(arel.where(category: "fruit", color: "green").map(&:name)).to eq %w(Pear Grape) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment