class Tml::Tokens::Decoration

Constants

RESERVED_TOKEN
TOKEN_PLACEHOLDER

Attributes

default_name[R]
full_name[R]
label[R]
short_name[R]

Public Class Methods

new(label, token) click to toggle source
# File lib/tml/tokens/decoration.rb, line 42
def initialize(label, token)
  @label = label
  @full_name = token.to_s
  @short_name = @full_name

  # removing the numbers at the end - default tokens don't need them
  @default_name = @short_name.gsub(/(\d)*$/, '')
end

Public Instance Methods

allowed?(allowed_tokens) click to toggle source
# File lib/tml/tokens/decoration.rb, line 80
def allowed?(allowed_tokens)
  return true if allowed_tokens.nil?
  allowed_tokens.include?(short_name)
end
apply(token_values, token_content, allowed_tokens = nil) click to toggle source
# File lib/tml/tokens/decoration.rb, line 85
def apply(token_values, token_content, allowed_tokens = nil)
  return token_content if short_name == RESERVED_TOKEN
  return token_content unless allowed?(allowed_tokens)

  method = Tml::Utils.hash_value(token_values, short_name)

  if method
    if method.is_a?(String)
      return method.to_s.gsub(TOKEN_PLACEHOLDER, token_content)
    end

    if method.is_a?(Proc)
      return method.call(token_content)
    end

    if method.is_a?(Array) || method.is_a?(Hash)
      return default_decoration(token_content, method)
    end

    return token_content
  end

  default_decoration(token_content)
end
default_decoration(token_content, decoration_token_values = nil) click to toggle source
# File lib/tml/tokens/decoration.rb, line 55
def default_decoration(token_content, decoration_token_values = nil)
  default_decoration = Tml.config.default_token_value(default_name, :decoration)

  unless default_decoration
    return "<#{short_name}>#{token_content}</#{short_name}>"
  end

  # {$0} always represents the actual content
  default_decoration = default_decoration.gsub(TOKEN_PLACEHOLDER, token_content.to_s)

  # substitute the token values with hash elements
  if decoration_token_values.is_a?(Hash)
    decoration_token_values.each do |key, value|
      default_decoration = default_decoration.gsub("{$#{key}}", value.to_s)
    end
  elsif decoration_token_values.is_a?(Array)
    decoration_token_values.each_with_index do |value, index|
      default_decoration = default_decoration.gsub("{$#{index + 1}}", value.to_s)
    end
  end

  # remove unused attributes
  default_decoration.gsub(/\{\$[^}]*\}/, '')
end
to_s() click to toggle source
# File lib/tml/tokens/decoration.rb, line 51
def to_s
  full_name
end