Sha256: 4216e64b818df28493d0843fb1c04e182bc0cb9307db2a033ce3487df289a378

Contents?: true

Size: 1.2 KB

Versions: 1

Compression:

Stored size: 1.2 KB

Contents

# encoding: utf-8

module Okei

  # Finds an unit by name:
  #
  #   use_case = GetUnit.new name: "1000 человеко-часов"
  #   use_case.run
  #   # => #<Okei::Unit @code: "ТЫС ЧЕЛ-ЧАС" ...>
  #
  # Any other parameters are ignored.
  #
  # Allows subscription before running:
  #
  #   use_case.subscribe logger
  #   use_case.subscribe controller
  #   use_case.run
  #
  class FindUnit < Hexx::UseCase
    include Wisper::Publisher

    allow_params :text

    # Runs the method:
    #
    # * оn success publishes `found(unit)` and returns an `unit`
    # * on error raises `Hexx::NotFoundError` with `self`
    #
    def run!
      unit_found?
      publish :found, unit
      unit
    end

    private

    def text
      @text ||= params["text"]
    end

    def line
      @line ||= Line.new text
    end

    def words
      @words ||= Words.new(line).map { |word| Word.translate word }
    end

    def code
      @code ||= Word.translate words.to_s
    end

    def unit
      @unit ||= Rails.cache.fetch(line) do
        Unit.find_by_code(code)
      end
    end

    def unit_found?
      return if unit
      errors.add :text, :not_found
      fail Hexx::NotFoundError.new self
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
okei-0.0.2 app/use_cases/okei/find_unit.rb