class RuboCop::Cop::Rails::RenderPlainText
render text: ‘Ruby!’
# bad - sets MIME type to ‘text/html`
@example ContentTypeCompatibility: false
render text: ’Ruby!‘
# good - sets MIME type to `text/html`
@example ContentTypeCompatibility: true (default)
render text: ’Ruby!‘, content_type: ’text/html’
# good - explicit MIME type not to ‘text/plain`
render plain: ’Ruby!‘
# good - short and precise
render text: ’Ruby!‘, content_type: ’text/plain’
# bad - explicit MIME type to ‘text/plain`
@example
replaced with `render plain:`.
Identifies places where `render text:` can be
def compatible_content_type?(pair_node)
def compatible_content_type?(pair_node) if pair_node.nil? !cop_config['ContentTypeCompatibility'] elsif pair_node.value.respond_to?(:value) pair_node.value.value == 'text/plain' end end
def find_content_type(node)
def find_content_type(node) node.pairs.find { |p| p.key.value.to_sym == :content_type } end
def on_send(node)
def on_send(node) render_plain_text?(node) do |options_node, option_node, option_value| content_type_node = find_content_type(options_node) return unless compatible_content_type?(content_type_node) add_offense(node) do |corrector| rest_options = options_node.pairs - [option_node, content_type_node].compact corrector.replace(node, replacement(rest_options, option_value)) end end end
def replacement(rest_options, option_value)
def replacement(rest_options, option_value) if rest_options.any? "render plain: #{option_value.source}, #{rest_options.map(&:source).join(', ')}" else "render plain: #{option_value.source}" end end