Created
April 29, 2011 15:24
-
-
Save jurgens/948456 to your computer and use it in GitHub Desktop.
Complex object matcher
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
module Kernel | |
def object_match?(a, b, cmp_key = 'guid') | |
cmp = lambda {|x,y| (x[cmp_key] <=> y[cmp_key]).to_i} | |
if a.kind_of? Hash | |
a.each do |key, value| | |
return false unless object_match?(value, b[key], cmp_key) | |
end | |
elsif a.kind_of? Array | |
a.sort!(&cmp) | |
b.sort!(&cmp) | |
a.each_index do |index| | |
return false unless object_match?(a[index], b[index], cmp_key) | |
end | |
else | |
a == b | |
end | |
end | |
end |
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' | |
require 'object_match' | |
describe Kernel do | |
describe "synthetic test" do | |
let(:a) { {:x => [{:a => 1}, {:a => 2}], :y => [{:a => 3}, {:a => 4}] } } | |
let(:b) { {:y => [{:a => 4}, {:a => 3}], :x => [{:a => 2}, {:a => 1}] } } | |
let(:c) { {:x => [{:a => 6}, {:a => 7}], :y => [{:a => 8}, {:a => 9}] } } | |
specify "should match" do | |
object_match?(a, b, 'a'.to_sym).should be_true | |
end | |
specify "should not match" do | |
object_match?(a, c, 'a'.to_sym).should be_false | |
end | |
end | |
describe "real life test" do | |
let(:a) { {"highlights"=>[{"guid"=>"444", "updated_at"=>1303761600, "id"=>"4", "verse_id"=>4, "word_id"=>4, "style"=>444}, {"guid"=>"222", "deleted"=>true}, {"guid"=>"111", "deleted"=>true}]} } | |
let(:b) { {"highlights"=>[{"guid"=>"111", "deleted"=>true}, {"guid"=>"444", "updated_at"=>1303761600, "id"=>"4", "verse_id"=>4, "word_id"=>4, "style"=>444}, {"guid"=>"222", "deleted"=>true}]} } | |
specify "should match" do | |
object_match?(a, b, 'guid').should be_true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment