Class: UcbRails::LdapPerson::Finder

Inherits:
Object
  • Object
show all
Defined in:
app/models/ucb_rails/ldap_person/finder.rb

Constant Summary collapse

BlankSearchTermsError =
Class.new(StandardError)
PersonNotFound =
Class.new(StandardError)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.klassObject



53
54
55
56
57
58
59
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 53

def klass
  if RailsEnvironment.test? || UcbRails[:omniauth_provider] == :developer
    UcbRails::LdapPerson::TestFinder
  else
    UcbRails::LdapPerson::Finder
  end
end

.method_missing(method, *args) ⇒ Object



61
62
63
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 61

def method_missing(method, *args)
  klass.new.send(method, *args)
end

Instance Method Details

#benchmark(message = "Benchmarking") ⇒ Object



6
7
8
9
10
11
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 6

def benchmark(message = "Benchmarking")
  result = nil
  ms = Benchmark.ms { result = yield }
  Rails.logger.debug "#{message} #{ms}"
  result
end

#build_filter(attrs) ⇒ Object



41
42
43
44
45
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 41

def build_filter(attrs)
  filter_parts = attrs.map { |k, v| build_filter_part(k, v) }
  filter = filter_parts.inject { |accum, filter| accum.send(:&, filter) }
  filter
end

#build_filter_part(key, value) ⇒ Object



47
48
49
50
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 47

def build_filter_part(key, value)
  value = key.to_s == 'uid' ? value : "#{value}*"
  Net::LDAP::Filter.eq(key.to_s, value)
end

#find_by_attributes(attributes) ⇒ Object



34
35
36
37
38
39
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 34

def find_by_attributes(attributes)
  attributes.each { |k, v| attributes.delete(k) if v.blank?  }
  UCB::LDAP::Person.
    search(:filter => build_filter(attributes)).
    map { |ldap_entry| Entry.new_from_ldap_entry(ldap_entry) }
end

#find_by_first_last(first_name, last_name, options = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 23

def find_by_first_last(first_name, last_name, options={})
  raise BlankSearchTermsError unless first_name.present? || last_name.present?
  
  find_by_attributes(:givenname => first_name, :sn => last_name).tap do |entries|
    if options[:sort]
      sort_symbol = options[:sort]
      entries.sort_by!(&options[:sort])
    end
  end
end

#find_by_uid(uid) ⇒ Object



13
14
15
16
17
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 13

def find_by_uid(uid)
  benchmark("find_by_uid(#{uid})") do
    find_by_attributes(:uid => uid.to_s).first
  end
end

#find_by_uid!(uid) ⇒ Object



19
20
21
# File 'app/models/ucb_rails/ldap_person/finder.rb', line 19

def find_by_uid!(uid)
  find_by_uid(uid) or raise(PersonNotFound, "uid=#{uid.inspect}")
end