Sha256: 4e7d7b7cd7cd49e0bff5d99da8fdf731956cc3f0804961917fb0d0c005bf35ab

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

module Mongoid
  module Haystack
    class Token
      include Mongoid::Document

      class << Token
        def values_for(*args)
          Haystack.stems_for(*args)
        end

        def add(value)
          token =
            Haystack.find_or_create(
              ->{ where(:value => value).first },
              ->{ create!(:value => value) }
            )

          token.inc(:count, 1)

          Count[:tokens].inc(1)

          token
        end

        def sequence
          Sequence.for(Token.name.scan(/[^:]+/).join('.').downcase)
        end

        def next_hex_id
          "0x#{ hex = sequence.next.to_s(16) }"
        end
      end

      field(:_id, :type => String, :default => proc{ Token.next_hex_id })
      field(:value, :type => String)
      field(:count, :type => Integer, :default => 0)

      index({:value => 1}, {:unique => true})
      index({:count => 1})

      def frequency(n_tokens = Count[:tokens].value.to_f)
        (count / n_tokens).round(2)
      end

      def frequency_bin(n_tokens = Count[:tokens].value.to_f)
        (frequency(n_tokens) * 10).truncate
      end

      def rarity(n_tokens = Count[:tokens].value.to_f)
        ((n_tokens - count) / n_tokens).round(2)
      end

      def rarity_bin(n_tokens = Count[:tokens].value.to_f)
        (rarity(n_tokens) * 10).truncate
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mongoid-haystack-1.1.0 lib/mongoid-haystack/token.rb