lib/opal/fragment.rb



module Opal
  # A fragment holds a string of generated javascript that will be written
  # to the destination. It also keeps hold of the original sexp from which
  # it was generated. Using this sexp, when writing fragments in order, a
  # mapping can be created of the original location => target location,
  # aka, source-maps!
  #
  # These are generated by nodes, so will not have to create directly.
  class Fragment
    # String of javascript this fragment holds
    # @return [String]
    attr_reader :code

    # Create fragment with javascript code and optional original [Opal::Sexp].
    #
    # @param code [String] javascript code
    # @param sexp [Opal::Sexp] sexp used for creating fragment
    def initialize(code, scope, sexp = nil)
      @code = code.to_s
      @sexp = sexp
      @scope = scope
    end

    # Inspect the contents of this fragment, f("fooo")
    def inspect
      "f(#{@code.inspect})"
    end

    def source_map_name
      return nil unless @scope
      def_node = @scope.def? ? @scope : @scope.find_parent_def
      def_node && def_node.mid
    end

    # Original line this fragment was created from
    # @return [Integer, nil]
    def line
      @sexp.line if @sexp
    end

    # Original column this fragment was created from
    # @return [Integer, nil]
    def column
      @sexp.column if @sexp
    end
  end
end