Sha256: c301ac8c0894379d43c59b7ef02ff8ec716563630b26eeccce6b28207e4e80e8

Contents?: true

Size: 864 Bytes

Versions: 5

Compression:

Stored size: 864 Bytes

Contents

# frozen_string_literal: true

##
# Bot lookup based on user agent
module Legitbot
  @rules = []

  class << self
    attr_accessor :resolver_config
  end

  ##
  # Lookup a bot based on its signature from +User-Agent+ header.
  #
  # If a block given, passes the found bot to the block.
  #
  # Returns +nil+ if no bot found and a bot match instance
  # otherwise.
  # :yields: a found bot
  #
  def self.bot(user_agent, ip)
    bots = @rules
           .select { |rule| rule[:fragments].any? { |f| user_agent.index f } }
           .map { |rule| rule[:class].new(ip) }

    selected = bots.select(&:valid?).first if bots.size > 1
    selected = bots.last if selected.nil?

    if selected && block_given?
      yield selected
    else
      selected
    end
  end

  def self.rule(clazz, fragments)
    @rules << { class: clazz, fragments: fragments }
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
legitbot-1.0.0 lib/legitbot/legitbot.rb
legitbot-0.4.3 lib/legitbot/legitbot.rb
legitbot-0.4.2 lib/legitbot/legitbot.rb
legitbot-0.4.1 lib/legitbot/legitbot.rb
legitbot-0.4.0 lib/legitbot/legitbot.rb