Skip to content

Commit

Permalink
Refactor Blacklight::Document#has? for clarity
Browse files Browse the repository at this point in the history
  • Loading branch information
cbeer committed Mar 20, 2015
1 parent cbee004 commit 0524986
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 8 deletions.
24 changes: 16 additions & 8 deletions lib/blacklight/document.rb
Expand Up @@ -80,21 +80,29 @@ def _read_attribute(attr)
# doc.has?(:location_facet, 'Clemons')
# doc.has?(:id, 'h009', /^u/i)
def has?(k, *values)
return true if key?(k) and values.empty?
return false if self[k].nil?
target = self[k]
if target.is_a?(Array)
values.each do |val|
return target.any?{|tv| val.is_a?(Regexp) ? (tv =~ val) : (tv==val)}
end
if !key?(k)
false
elsif values.empty?
self[k].present?
else
return values.any? {|val| val.is_a?(Regexp) ? (target =~ val) : (target == val)}
Array(values).any? do |expected|
Array(self[k]).any? do |actual|
case expected
when Regexp
actual =~ expected
else
actual == expected
end
end
end
end
end
alias_method :has_field?, :has?

def key? k
_source.key? k
end
alias_method :has_key?, :key?

# helper
# key is the name of the field
Expand Down
62 changes: 62 additions & 0 deletions spec/lib/blacklight/document_spec.rb
@@ -0,0 +1,62 @@
require 'spec_helper'

describe Blacklight::Document do
let(:data) { {} }
subject do
Class.new do
include Blacklight::Document
end.new(data)
end

describe "#has?" do
context "without value constraints" do
it "should have the field if the field is in the data" do
data[:x] = true
expect(subject).to have_field(:x)
end

it "should not have the field if the field is not in the data" do
expect(subject).not_to have_field(:x)
end
end

context "with regular value constraints" do
it "should have the field if the data has that value" do
data[:x] = true
expect(subject).to have_field(:x, true)
end

it "should not have the field if the data does not have that value" do
data[:x] = false
expect(subject).not_to have_field(:x, true)
end

it "should allow multiple value constraints" do
data[:x] = false
expect(subject).to have_field(:x, true, false)
end

it "should support multivalued fields" do
data[:x] = ["a", "b", "c"]
expect(subject).to have_field(:x, "a")
end

it "should support multivalued fields with an array of value constraints" do
data[:x] = ["a", "b", "c"]
expect(subject).to have_field(:x, "a", "d")
end
end

context "with regexp value constraints" do
it "should check if the data matches the constraint" do
data[:x] = "the quick brown fox"
expect(subject).to have_field(:x, /fox/)
end

it "should support multivalued fields" do
data[:x] = ["the quick brown fox", "and the lazy dog"]
expect(subject).to have_field(:x, /fox/)
end
end
end
end

0 comments on commit 0524986

Please sign in to comment.