Commit 701aa31c authored by Rene Saarsoo's avatar Rene Saarsoo
Browse files

JsLiteralBuilder class.

Simple helper to turn JsLiteralParser output back into string.
parent 83ef80e6
Loading
Loading
Loading
Loading
+21 −0
Original line number Diff line number Diff line
module JsDuck

  # Takes output of JsLiteralParser and converts it to string
  class JsLiteralBuilder

    # Converts literal object definition to string
    def to_s(lit)
      if lit[:type] == :string
        '"' + lit[:value] + '"'
      elsif lit[:type] == :array
        "[" + lit[:value].map {|v| to_s(v) }.join(", ") + "]"
      elsif lit[:type] == :object
        "{" + lit[:value].map {|v| to_s(v[:key]) + ": " + to_s(v[:value]) }.join(", ") + "}"
      else
        lit[:value]
      end
    end

  end

end
+36 −0
Original line number Diff line number Diff line
require "jsduck/js_literal_builder"

describe JsDuck::JsLiteralBuilder do

  def build(obj)
    JsDuck::JsLiteralBuilder.new.to_s(obj)
  end

  it "builds number" do
    build({:type => :number, :value => "5"}).should == "5"
  end

  it "builds string" do
    build({:type => :string, :value => "5"}).should == '"5"'
  end

  it "builds regex" do
    build({:type => :regex, :value => "/[a-z]/i"}).should == '/[a-z]/i'
  end

  it "builds array" do
    build({:type => :array, :value => [
          {:type => :number, :value => "1"},
          {:type => :number, :value => "2"}
        ]}).should == '[1, 2]'
  end

  it "parses object" do
    build({:type => :object, :value => [
          {:key => {:type => :ident, :value => "foo"}, :value => {:type => :number, :value => "1"}},
          {:key => {:type => :string, :value => "bar"}, :value => {:type => :number, :value => "2"}}
        ]}).should == '{foo: 1, "bar": 2}'
  end

end