Module: Cecil::Lang::TypeScript::Helpers

Includes:
Code::Helpers
Defined in:
lib/cecil/lang/typescript.rb

Instance Method Summary collapse

Instance Method Details

#j(item) ⇒ String

Short for "json"; returns the JSON representation of the input.

Useful for when you have a value in Ruby and you want it as a literal value in the JavaScript/TypeScript source code.

Examples:

current_user = { name: "Bob" }
`const user = $user_obj`[j current_user]

# outputs:
# const user = {"name":"Bob"}

Parameters:

  • item (#to_json)

    Any object that responds to #to_json

Returns:

  • (String)

    JSON representation of the input



59
# File 'lib/cecil/lang/typescript.rb', line 59

def j(item) = item.to_json

#l(items) ⇒ String

Short for "list"; Accepts one or a list of strings and returns them joined with ", "

Examples:

the_classes = ["Websocket", "Array", "Function"]
`register($args)`[l the_classes]

# outputs:
# register(Websocket, Array, Function)

Parameters:

  • items (Array[#to_s], #to_s)

    One or a list of objects that respond to #to_s

Returns:

  • (String)

    The stringified inputs concatenated with ", "



43
# File 'lib/cecil/lang/typescript.rb', line 43

def l(items) = Array(items).compact.join(", ")

#s(item) ⇒ String

Short for "string content"; returns a JSON string without quotes.

Useful for inserting data into a string or for outputting a string but using quotes to make it clear to the reader what the intended output will be.

It also escapes single quotes and backticks so that it can be inserted into single-quoted strings and string templates.

Examples:

Inserting into a string

name = "Bob \"the Machine\" O'Brian"
`const admin = "$name (Admin)"`[s name]

# outputs:
# const admin = "Bob \"the Machine\" O\'Brian (Admin)"

Outputting what is obviously a string

name = "Bob \"the Machine\" O'Brian"
`const admin = "$name"`[s name]

# outputs:
# const admin = "Bob \"the Machine\" O\'Brian"

Parameters:

  • item (#to_s)

    A string or any object that responds to #to_s

Returns:

  • (String)

    A JSON string without quotes



85
# File 'lib/cecil/lang/typescript.rb', line 85

def s(item) = item.to_s.to_json[1...-1].gsub("'", "\\\\'").gsub("`", "\\\\`")

#t(items) ⇒ String

Short for "types"; Accepts one or a list of types and returns their union.

Examples:

the_types = ["Websocket", "undefined", "null"]
`function register<$types>() {}`[t the_types]

# outputs:
# function register<Websocket | undefined | null>() {}

Parameters:

  • items (Array[#to_s], #to_s)

    One or a list of objects that respond to #to_s

Returns:

  • (String)

    The stringified inputs concatenated with " | "



30
# File 'lib/cecil/lang/typescript.rb', line 30

def t(items) = Array(items).compact.join(" | ")