class Slimcop::RubyExtractor

Extract Ruby codes from Slim source.

Public Class Methods

call( file_path:, source: ) click to toggle source

@param [String, nil] file_path @param [String] source

# File lib/slimcop/ruby_extractor.rb, line 12
def call(
  file_path:,
  source:
)
  new(
    file_path: file_path,
    source: source
  ).call
end
new(file_path:, source:) click to toggle source

@param [String, nil] file_path @param [String] source

# File lib/slimcop/ruby_extractor.rb, line 25
def initialize(file_path:, source:)
  @file_path = file_path
  @source = source
end

Public Instance Methods

call() click to toggle source

@return [Array<Hash>]

# File lib/slimcop/ruby_extractor.rb, line 31
def call
  ranges.map do |(begin_, end_)|
    clipped = ::Templatecop::RubyClipper.new(@source[begin_...end_]).call
    {
      code: clipped[:code],
      offset: begin_ + clipped[:offset]
    }
  end
end

Private Instance Methods

ast() click to toggle source

@return [Array] Slim AST, represented in S-expression.

# File lib/slimcop/ruby_extractor.rb, line 44
def ast
  ::Slimi::Filters::Interpolation.new.call(
    ::Slimi::Parser.new(file: @file_path).call(@source)
  )
end
ranges() click to toggle source

@return [Array<Array<Integer>>]

# File lib/slimcop/ruby_extractor.rb, line 51
def ranges
  result = []
  traverse(ast) do |begin_, end_|
    result << [begin_, end_]
  end
  result
end
traverse(node, &block) click to toggle source
# File lib/slimcop/ruby_extractor.rb, line 59
def traverse(node, &block)
  return unless node.instance_of?(::Array)

  if node[0] == :slimi && node[1] == :position
    block.call(node[2], node[3])
  else
    node.each do |element|
      traverse(element, &block)
    end
  end
end