class Erbcop::RubyExtractor

Extract Ruby codes from Erb source.

Public Class Methods

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

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

# File lib/erbcop/ruby_extractor.rb, line 13
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/erbcop/ruby_extractor.rb, line 26
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/erbcop/ruby_extractor.rb, line 32
def call
  nodes.map do |node|
    snippet = node.children.first
    clipped = ::Templatecop::RubyClipper.new(snippet).call
    {
      code: clipped[:code],
      offset: node.location.begin_pos + clipped[:offset]
    }
  end
end

Private Instance Methods

erbs() click to toggle source

@return [Array<BetterHtml::AST::Node>]

# File lib/erbcop/ruby_extractor.rb, line 46
def erbs
  root.descendants(:erb).reject do |erb|
    erb.children.first&.type == :indicator && erb.children.first&.to_a&.first == '#'
  end
end
nodes() click to toggle source

@return [Enumerator<BetterHtml::AST::Node>]

# File lib/erbcop/ruby_extractor.rb, line 53
def nodes
  erbs.flat_map do |erb|
    erb.descendants(:code).to_a
  end
end
root() click to toggle source

@return [BetterHtml::AST::Node]

# File lib/erbcop/ruby_extractor.rb, line 60
def root
  ::BetterHtml::Parser.new(
    ::Parser::Source::Buffer.new(
      @file_path,
      source: @source
    ),
    template_language: :html
  ).ast
end