Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for creating a Jsgf object from a string #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions lib/pocketsphinx/grammar/jsgf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,24 @@ module Grammar
class Jsgf
attr_reader :raw

def initialize(path = nil, &block)
if path.nil? && !block_given?
# A convenience method for creating a new {Jsgf} from a string
# @param jsgf_string [String] the JSGF string to use
def self.from_string(jsgf_string)
self.new(nil, jsgf_string)
end

# @param path [String] the path to the file to be loaded
# @param jsgf [String] a string to be parsed as a JSGF grammar (set path to nil)
def initialize(path = nil, jsgf = nil, &block)
if path.nil? && jsgf.nil? && !block_given?
raise "Either a path or block is required to create a JSGF grammar"
end

if block_given?
@raw = grammar_from_block(&block)
elsif jsgf
@raw = jsgf
check_grammar
else
@raw = grammar_from_file(path)
check_grammar
Expand All @@ -30,7 +41,7 @@ def grammar_from_block(&block)

def check_grammar
# Simple header check for now
raise 'Invalid JSGF grammar' unless raw.lines.first.strip == "#JSGF V1.0;"
raise 'Invalid JSGF grammar' unless raw.lines.first && raw.lines.first.strip == "#JSGF V1.0;"
end
end
end
Expand Down
13 changes: 13 additions & 0 deletions spec/grammar_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@
end
end

context "building a grammar from a string" do
it "stores the string" do
grammar = Pocketsphinx::Grammar::Jsgf.from_string("#JSGF V1.0;\ngrammar turtle;\npublic <turtle> = go forward ten meters;")
expect(grammar.raw.lines.count).to eq(3)
end

context "the grammar string is invalid" do
it "raises an exception" do
expect { Pocketsphinx::Grammar::Jsgf.from_string("") }.to raise_exception "Invalid JSGF grammar"
end
end
end

private

def grammar(name)
Expand Down