Class: LoremJP

Inherits:
Object
  • Object
show all
Defined in:
lib/lorem_jp.rb,
lib/lorem_jp/cli.rb

Overview

Class for Japanese Lorem Ipsum generation

Defined Under Namespace

Classes: CLI

Constant Summary collapse

VERSION =

Version number

'0.0.1'
DICTIONARY_DIR =

Default dictionary directory

File.absolute_path('../../data', __FILE__)
DEFAULT_DICTIONARY =

Default dictionary file

File.join(DICTIONARY_DIR, 'dict.txt')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ LoremJP

Returns a new instance of LoremJP.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :dictionary (String)

    file name of dictionary

  • :lazy (Boolean)

    load dictionary file on first generation if true



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/lorem_jp.rb', line 41

def initialize(options = {})
  @dictionary = options[:dictionary]
  @chain      = options[:chain] || 1

  lazy = options[:lazy] || false

  @dict   = []
  @tree   = {}
  @loaded = false

  if ! lazy
    load_dict(@dictionary)
  end
end

Class Method Details

.sentence(options = {}) ⇒ String

Singleton interface of #sentence

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :chain (Integer)

    number of words considered as past state in Marcov chain

  • :dictionary (String)

    file name of dictionary

Returns:

  • (String)

    Japanese meaningless sentence



21
22
23
# File 'lib/lorem_jp.rb', line 21

def sentence(options = {})
  return singleton_for_dict(options[:dictionary]).sentence(options)
end

Instance Method Details

#sentence(options = {}) ⇒ String

Returns Japanese meaningless sentence.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :chain (Integer)

    number of words considered as past state in Marcov chain

Returns:

  • (String)

    Japanese meaningless sentence



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/lorem_jp.rb', line 60

def sentence(options = {})
  unless @loaded
    load_dict(@dictionary)
  end

  chain = options[:chain] || @chain

  unless chain > 0
    raise ArgumentError,
          "invalid chain option value (#{chain})."
  end
  unless chain <= @chain
    raise ArgumentError,
          "chain option value (#{chain}) exceeds dict's chain (#{@chain})"
  end

  tokens = []
  stack = [ 0 ] * chain

  loop do
    cands = lookup_candidates(stack)
    cand = cands[rand(cands.length)]
    break if cand < 0   # EOS

    tokens << @dict[cand]

    stack.shift
    stack << cand
  end

  return tokens.join('')
end