Sha256: 90fed76b5e45331cfe1690af8cfe33adca10b629b368a871d81da9d6a16f307d

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

require 'speed_gun/store'

class SpeedGun::Store::ElasticSearchStore < SpeedGun::Store
  DEFAULT_INDEX = 'speed_gun'

  def initialize(options = {})
    @index = options[:index] || DEFAULT_INDEX
    @async = options.fetch(:async, true)
    @client = options[:client] || default_clinet(options)
  end

  def save(object)
    @async ? save_with_async(object) : save_without_async(object)
  end

  def load(klass, id)
    hit = @client.search(
      index: @index,
      body: {
        query: {
          match: {
            "_id" => id,
            "_type" => underscore(klass.name)
          }
        }
      }
    )['hits']['hits'].first['_source']

    klass.from_hash(id, hit)
  end

  private

  def save_with_async(object)
    Thread.new(object) { |object| save_without_async(object) }
  end

  def save_without_async(object)
    @client.index(
      index: @index,
      type: underscore(object.class.name),
      id: object.id,
      body: object.to_hash.merge(
        '@timestamp' => Time.now
      )
    )
  end

  def index(klass)
    [@prefix, underscore(klass.name)].join('-')
  end

  def underscore(name)
    name = name
    name.sub!(/^[A-Z]/) { |c| c.downcase }
    name.gsub!(/[A-Z]/) { |c| "_#{c.downcase}" }
    name.gsub!('::', '')
  end

  def default_clinet(options)
    require 'elasticsearch' unless defined?(Elasticsearch)
    Elasticsearch::Client.new(options)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
speed_gun-1.0.0.rc1 lib/speed_gun/store/elastic_search_store.rb