Class: Babelfish::Phrase::Compiler
- Inherits:
-
Object
- Object
- Babelfish::Phrase::Compiler
- Defined in:
- lib/babelfish/phrase/compiler.rb
Overview
Babelfish AST Compiler. Compiles AST to string or to Proc.
Instance Attribute Summary collapse
-
#ast ⇒ Object
Returns the value of attribute ast.
Instance Method Summary collapse
-
#compile(ast) ⇒ Object
Result is string when possible; Proc otherwise.
-
#init(ast) ⇒ Object
Initializes compiler.
-
#initialize(ast = nil) ⇒ Compiler
constructor
A new instance of Compiler.
-
#throw(message) ⇒ Object
Throws given message in compiler context.
Constructor Details
#initialize(ast = nil) ⇒ Compiler
Returns a new instance of Compiler.
13 14 15 |
# File 'lib/babelfish/phrase/compiler.rb', line 13 def initialize( ast = nil ) init( ast ) unless ast.nil? end |
Instance Attribute Details
#ast ⇒ Object
Returns the value of attribute ast.
11 12 13 |
# File 'lib/babelfish/phrase/compiler.rb', line 11 def ast @ast end |
Instance Method Details
#compile(ast) ⇒ Object
Result is string when possible; Proc otherwise.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/babelfish/phrase/compiler.rb', line 30 def compile ( ast ) init( ast ) unless ast.nil? throw("No AST given") if ast.nil? throw("Empty AST given") if ast.length == 0; if ast.length == 1 && ast.first.kind_of?(Babelfish::Phrase::Literal) # просто строка return ast.first.text end ready = ast.map do |node| case node when Babelfish::Phrase::Literal node.text when Babelfish::Phrase::Variable node when Babelfish::Phrase::PluralForms sub = node.to_ruby_method else throw("Unknown AST node: #{node}") end end lambda do |params| data = ready.map do |what| case what when Babelfish::Phrase::Variable params[what.name.to_s].to_s when Proc what = what.call(params) else what end end.join('') data end end |
#init(ast) ⇒ Object
Initializes compiler. Should not be called directly.
18 19 20 |
# File 'lib/babelfish/phrase/compiler.rb', line 18 def init( ast ) self.ast = ast end |
#throw(message) ⇒ Object
Throws given message in compiler context.
23 24 25 |
# File 'lib/babelfish/phrase/compiler.rb', line 23 def throw( ) raise "Cannot compile: #{}"; end |