Module: Browscapper

Defined in:
lib/browscapper.rb,
lib/browscapper/reader.rb,
lib/browscapper/version.rb,
lib/browscapper/user_agent.rb,
lib/browscapper/reader/csv_reader.rb,
lib/browscapper/reader/ini_reader.rb,
lib/browscapper/reader/yaml_reader.rb,
lib/browscapper/reader/marshal_reader.rb

Defined Under Namespace

Modules: CSVReader, INIReader, MarshalReader, Reader, YAMLReader Classes: UserAgent

Constant Summary collapse

MATCH_CACHE =
Hash.new
VERSION =
"0.2.0"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.entriesObject (readonly)

Returns the value of attribute entries.



14
15
16
# File 'lib/browscapper.rb', line 14

def entries
  @entries
end

.fileObject (readonly)

Returns the value of attribute file.



14
15
16
# File 'lib/browscapper.rb', line 14

def file
  @file
end

Class Method Details

.clear_cacheObject



39
40
41
# File 'lib/browscapper.rb', line 39

def clear_cache
  MATCH_CACHE.clear
end

.load(file = File.join(%w{ . browscap.ini })) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/browscapper.rb', line 17

def load(file = File.join(%w{ . browscap.ini }))
  if !File.exists?(file)
    raise ArgumentError.new("File #{file} not found.")
  end

  reader = case file.downcase
    when /\.csv$/
      CSVReader
    when /\.ya?ml$/
      YAMLReader
    when /\.ini$/
      INIReader
    else
      MarshalReader
  end

  @file = file
  @entries = reader.load(file)
  clear_cache
  self
end

.match(ua) ⇒ Object Also known as: query



60
61
62
63
64
65
66
67
68
69
# File 'lib/browscapper.rb', line 60

def match(ua)
  return nil if ua_empty?(ua)

  if MATCH_CACHE[ua] && !MATCH_CACHE[ua].empty?
    MATCH_CACHE[ua].first
  else
    m = self.matches(ua)
    m.first if !m.empty?
  end
end

.matches(ua) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/browscapper.rb', line 43

def matches(ua)
  return nil if ua_empty?(ua)

  @entries or self.load

  ua_str = ua.to_s.downcase
  ua_len = ua_str.length

  MATCH_CACHE[ua] ||= @entries.select { |k, v|
    v[:pattern] =~ ua_str if v
  }.sort_by { |(k, v)|
    ua_len - v[:user_agent].gsub(/[?*]/, '').length
  }.collect { |(k, v)|
    v
  }
end