Sha256: d52f7cf76023f2fc9b67429c35c84d92cd6c2bac4fdf255559f5d519dd8baecb

Contents?: true

Size: 1.47 KB

Versions: 11

Compression:

Stored size: 1.47 KB

Contents

module Unitwise
  # The search module provides a simple search mechanism around known basic
  # units. The full list of avaliable units infinite, so this search creates
  # a small subset of atoms and prefixes to help users find what they are
  # looking for. Thus, there is a multitude of valid units that may be
  # constructed that this module will not be aware of.
  module Search
    class << self
      # An abbreviated list of possible units. These are known combinations
      # of atoms and prefixes.
      # @return [Array] A list of known units
      # @api public
      def all
        @all ||= begin
          units = []
          Atom.all.each do |a|
            units << build(a)
            Unitwise::Prefix.all.each { |p| units << build(a, p) } if a.metric?
          end
          units
        end
      end

      # Search the list of known units for a match.
      # @param term [String, Regexp] The term to search for
      # @return [Array] A list of matching units.
      # @api public
      def search(term)
        all.select do |unit|
          unit.aliases.any? { |str| Regexp.new(term).match(str) }
        end
      end

      private

      # Helper method for building a new unit by a known atom and prefix.
      # @param atom [Unitwise::Atom]
      # @param prefix [Unitwise::Prefix, nil]
      # @return [Unitwise::Unit]
      # @api private
      def build(atom, prefix = nil)
        Unit.new([Term.new(:atom => atom, :prefix => prefix)])
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
unitwise-2.3.0 lib/unitwise/search.rb
unitwise-2.2.0 lib/unitwise/search.rb
unitwise-2.1.0 lib/unitwise/search.rb
unitwise-2.0.0 lib/unitwise/search.rb
unitwise-1.1.0 lib/unitwise/search.rb
unitwise-193-1.0.4 lib/unitwise/search.rb
unitwise-1.0.4 lib/unitwise/search.rb
unitwise-1.0.3 lib/unitwise/search.rb
unitwise-1.0.2 lib/unitwise/search.rb
unitwise-1.0.1 lib/unitwise/search.rb
unitwise-1.0.0 lib/unitwise/search.rb