class Bonsai::Searchkick::Railtie

Use Railties

Attributes

filtered_url[R]
logger[R]
port[R]
ported_url[R]
url[R]

Public Class Methods

new() click to toggle source

Method to determine what happens when an instance of this class is initialized

# File lib/bonsai/searchkick/railtie.rb, line 20
def initialize

  # Append a method to the String class so we can get a nice way to check
  # that a String is a valid URL. `_searchkick_` is part of the method
  # name to avoid possible collisions.
  String.class_eval do
      def is_valid_searchkick_url?
          uri = URI.parse self
          uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
      rescue URI::InvalidURIError
          false
      end
  end

  # Class attributes
  @logger = Logger.new(STDOUT)
  @url = ENV['BONSAI_URL'] || ENV['ELASTICSEARCH_URL'] || ''
  @port = searchkick_port
  @ported_url = maybe_add_port
  @filtered_url = filtered_url
end

Public Instance Methods

is_valid_searchkick_url?() click to toggle source
# File lib/bonsai/searchkick/railtie.rb, line 26
def is_valid_searchkick_url?
    uri = URI.parse self
    uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
rescue URI::InvalidURIError
    false
end
maybe_add_port() click to toggle source

Append a port to the URL string if necessary.

The Elasticsearch-ruby gem that Searchkick uses introduced a bug into its URL-parsing. Essentially, it will always assume port 9200, regardless of the protocol used. In other words, if you initialize the client with my-cluster.com, it will assume that you mean my-cluster.com:9200 and not my-cluster.com:443 (the standard port for HTTPS).

This method will ensure the URL port is correctly called out when using a Bonsai cluster.

Returns

* A String for the URL, possibly appended with a Bonsai-supported
  port.
# File lib/bonsai/searchkick/railtie.rb, line 71
def maybe_add_port
  if ENV['BONSAI_URL'].present?
    uri = URI.parse(@url) rescue ''
    if uri.kind_of?(URI::HTTPS) || uri.kind_of?(URI::HTTP)
      port = (uri.kind_of?(URI::HTTPS)) ? 443 : 80
      if !@port.present?
        @logger.debug("Bonsai: Appending port #{port} to the cluster URL for production environment.")
        return "#{@url}:#{port}".gsub('::', ':')
      elsif @port != port
        @logger.debug("Bonsai: Overriding the requested port #{@port} with the standard #{port} for production environment.")
        return "#{@url.rpartition(':').first}:#{port}"
      end
    end
  end
  @url
end
searchkick_port() click to toggle source

Check the URL for a port.

Returns

* An Integer representing the port, or nil if no port is given.
# File lib/bonsai/searchkick/railtie.rb, line 47
def searchkick_port
  return nil unless @url.is_valid_searchkick_url?

  port = @url[/:([0-9]{0,5}$)/, 1]
  return port.to_i if port.present?
  nil
end