Class: RuboCop::Markdown::Preprocess
- Inherits:
-
Object
- Object
- RuboCop::Markdown::Preprocess
- Defined in:
- lib/rubocop/markdown/preprocess.rb
Overview
Transform source Markdown file into valid Ruby file by commenting out all non-code lines
Constant Summary collapse
- MD_REGEXP =
This is a regexp to parse code blocks from .md files.
Only recognizes backticks-style code blocks.
/ ^([[:blank:]]*`{3,4}) # Match opening backticks ([\w[[:blank:]]+]*)?\n # Match the code block syntax ([\s\S]+?) # Match everything inside the code block (^[[:blank:]]*\1[[:blank:]]*\n?) # Match closing backticks |(^.*$) # If we are not in a codeblock, match the whole line /x.freeze
- MARKER =
"<--rubocop/md-->"- RUBY_TYPES =
%w[ ruby jruby macruby rake rb rbx ].freeze
Instance Attribute Summary collapse
-
#config ⇒ Object
readonly
Returns the value of attribute config.
Class Method Summary collapse
- .restore!(src) ⇒ Object
-
.restore_and_save!(file) ⇒ Object
Revert preprocess changes.
Instance Method Summary collapse
-
#call(src) ⇒ Object
rubocop:disable Metrics/MethodLength.
-
#initialize(file) ⇒ Preprocess
constructor
A new instance of Preprocess.
Constructor Details
#initialize(file) ⇒ Preprocess
Returns a new instance of Preprocess.
55 56 57 |
# File 'lib/rubocop/markdown/preprocess.rb', line 55 def initialize(file) @config = Markdown.config_store.for(file) end |
Instance Attribute Details
#config ⇒ Object (readonly)
Returns the value of attribute config.
53 54 55 |
# File 'lib/rubocop/markdown/preprocess.rb', line 53 def config @config end |
Class Method Details
.restore!(src) ⇒ Object
48 49 50 |
# File 'lib/rubocop/markdown/preprocess.rb', line 48 def restore!(src) src.gsub!(/^#\s*#{MARKER}/m, "") end |
.restore_and_save!(file) ⇒ Object
Revert preprocess changes.
When autocorrect is applied, RuboCop re-writes the file using preproccessed source buffer.
We have to restore it.
42 43 44 45 46 |
# File 'lib/rubocop/markdown/preprocess.rb', line 42 def restore_and_save!(file) contents = File.read(file) restore!(contents) File.write(file, contents) end |
Instance Method Details
#call(src) ⇒ Object
rubocop:disable Metrics/MethodLength
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/rubocop/markdown/preprocess.rb', line 60 def call(src) src.gsub(MD_REGEXP) do |full_match| m = Regexp.last_match open_backticks = m[1] syntax = m[2] code = m[3] close_backticks = m[4] markdown = m[5] if markdown # We got markdown outside of a codeblock comment_lines(markdown) elsif ruby_codeblock?(syntax, code) # The codeblock we parsed is assumed ruby, keep as is and append markers to backticks "#{comment_lines(open_backticks + syntax)}\n#{code}#{comment_lines(close_backticks)}" else # The codeblock is not relevant, comment it out comment_lines(full_match) end end end |