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



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

def j(item) = item.to_json

#l(items) ⇒ String

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

Useful for:

  • arrays
  • objects
  • function arguments

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 ", "



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

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

#s(item) ⇒ String

Short for "string content"; returns escaped version of the string that can be inserted into a JavaScript string literal or template literal.

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 literal

name = %q{Bob "the Machine" O'Brian}
`const admin = "$name (Admin)"`[s name]

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

Make your code communicate that a value will be a string

name = %q{Bob "the Machine" O'Brian}
`const admin = "$name"`[s name]

# We could use the `#j` helper, too, but `#s` and quotes makes it clearer that the value will be a string
`const admin = $name`[j name]

Parameters:

  • item (#to_s)

    A string or any object that responds to #to_s

Returns:

  • (String)

    A JSON string without quotes



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

def s(item) = item.to_s.to_json[1...-1].gsub(/['`\$]/) { "\\#{_1}" }

#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(" | ")