Code Monkey home page Code Monkey logo

plugin-ruby's Introduction

Prettier Banner

Opinionated Code Formatter

JavaScript · TypeScript · Flow · JSX · JSON
CSS · SCSS · Less
HTML · Vue · Angular
GraphQL · Markdown · YAML
Your favorite language?

Github Actions Build Status Github Actions Build Status Github Actions Build Status Codecov Coverage Status Blazing Fast
npm version weekly downloads from npm code style: prettier Follow Prettier on Twitter

Intro

Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.

Input

foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());

Output

foo(
  reallyLongArg(),
  omgSoManyParameters(),
  IShouldRefactorThis(),
  isThereSeriouslyAnotherOne(),
);

Prettier can be run in your editor on-save, in a pre-commit hook, or in CI environments to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again!


Documentation

Install · Options · CLI · API

Playground


Badge

Show the world you're using Prettiercode style: prettier

[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

Contributing

See CONTRIBUTING.md.

plugin-ruby's People

Contributors

alanfoster avatar andyw8 avatar ayrton avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dleavitt avatar drbragg avatar flyerhzm avatar gin0606 avatar github-actions[bot] avatar hrabe avatar ianks avatar janklimo avatar janpio avatar johnschoeman avatar kddnewton avatar localhostdotdev avatar meleyal avatar mhssmnn avatar mikesea avatar nbudin avatar phacks avatar rdimartino avatar rsullivan00 avatar ryan-hunter-pc avatar ryanseys avatar tobyndockerill avatar valscion avatar ykpythemind avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

plugin-ruby's Issues

Comment edge case

Input

def create
  if foo?
    # Relevant useful comment
    head :no_content
    return true
  end

  do_things
end

Current output

Comment is no longer in the correct place

def create
  if foo?
    head :no_content
    return true
  end
  # Relevant useful comment

  do_things
end

Expected output

def create
  if foo?
    # Relevant useful comment
    head :no_content
    return true
  end

  do_things
end

Format failed while converting JSON string

Input

# Code snippet
response = "{\"success\":true,\"message\":null,\"data\":#{array_containing_data}}"
render json: response

Current output

# Code snippet, or crash details
response =
      "{undefinedsuccessundefined:true,undefinedmessageundefined:null,undefineddataundefined:#{array_containing_data}}"
    render json: response

Expected output

I wasn't expecting it to replace some characters with undefined

Not keyword support

Input

if not foo?
  puts "hello world"
end

Current output

puts 'hello world' if nfoo?

Expected output

if not foo?
  puts "hello world"
end

Invalid trailing comma with trailingComma: true

Input

def handle_error_in_development(e)
  render json: {
    error: { message: e.message, backtrace: e.backtrace }, data: {},
  },
  status: 500
end

Current output

The comma after status: 500 makes this ruby invalid.

def handle_error_in_development(e)
  render json: {
    error: { message: e.message, backtrace: e.backtrace }, data: {},
  },
  status: 500,
end

Expected output

The following or some other valid ruby syntax.

def handle_error_in_development(e)
  render(
    json: { error: { message: e.message, backtrace: e.backtrace }, data: {} },
    status: 500,
  )
end

FWIW running --debug-check as suggested in #45 was helpful for me

Invalid shorthand generation

When running prettier it seems to break the following code snippet:

-    respond_to do |format|
-      format.xml
-    end
+    respond_to(&:format)

I believe it should've been prettied as respond_to(&:xml) - or leaving it as-is, as it's not idiomatic to use this style within respond_to blocks usually 🤔

Regex flags are stripped

Metadata

  • Ruby version: 2.5.1
  • @prettier/plugin-ruby version: 0.6.1

Input

foo(/x/m)

Current output

foo(/x/)

Expected output

foo(/x/m)

Single quotes not formatted correctly

Hey, I ran into an issue when formatting single quotes

Input file

"you're"

Current output file

'you're'

Expected output file

Current prettier for JS formats this with double quotes still

"you're"

Strips comments when converting from [] to %w[]

Metadata

  • Ruby version: 2.5.1
  • @prettier/plugin-ruby version: 0.6.1

Input

  TEST = [
    "1", # 1
    "2"  # 2
  ]

Current output

  TEST = %w[1 2] # 2

Expected output

Should be unchanged as you can't inline comments in %w's afaik.

  TEST = [
    "1", # 1
    "2"  # 2
  ]

TypeError: Cannot read property 'type' of undefined

for this file: https://github.com/leihs/leihs_legacy/blob/fc38cc0cedd77182f423d29bf49ed0454a54f0d0/app/models/setting.rb

app/models/setting.rb
[error] app/models/setting.rb: TypeError: Cannot read property 'type' of undefined
[error]     at Object.next (/Users/mfa/CODE/leihs/legacy/node_modules/@prettier/plugin-ruby/src/nodes.js:421:22)
[error]     at Object.module.exports [as print] (/Users/mfa/CODE/leihs/legacy/node_modules/@prettier/plugin-ruby/src/print.js:8:32)
[error]     at callPluginPrintFunction (/Users/mfa/CODE/leihs/legacy/node_modules/prettier/bin-prettier.js:13590:18)
[error]     at /Users/mfa/CODE/leihs/legacy/node_modules/prettier/bin-prettier.js:13541:16
[error]     at Object.printComments (/Users/mfa/CODE/leihs/legacy/node_modules/prettier/bin-prettier.js:13264:17)
[error]     at printGenerically (/Users/mfa/CODE/leihs/legacy/node_modules/prettier/bin-prettier.js:13540:22)
[error]     at FastPath.call (/Users/mfa/CODE/leihs/legacy/node_modules/prettier/bin-prettier.js:13378:16)
[error]     at path.getValue.body.forEach (/Users/mfa/CODE/leihs/legacy/node_modules/@prettier/plugin-ruby/src/nodes.js:507:28)
[error]     at Array.forEach (<anonymous>)
[error]     at Object.stmts (/Users/mfa/CODE/leihs/legacy/node_modules/@prettier/plugin-ruby/src/nodes.js:502:26)

Sidenote: That was the only error in ~12k formatted lines, so good job so far 👍
leihs/leihs_legacy@818678a

Usage with prettier-atom

I'm trying to setup this plugin to use prettier with our ruby files and for it to run in Atom.
Just installed the plugin and headed to a .rb file, and I'm getting the following error:

prettier-atom failed: Invalid trailingComma value. Expected true or false, but received "all".

I guess the issue is we already have a .prettierrc for the js config, and the options are not the same.
How should we specify one config for js and another for ruby?

Figure out & document how to disable RuboCop's styling rules

Welcome to the prettier org! So awesome.

As this project likely to live along-side RuboCop in Ruby projects we'll need to either document how to ensure that the two projects don't clash, or build something similar to https://github.com/prettier/eslint-plugin-prettier to ensure the two don't step on each others toes.

Ideas:

Incorrect argument formatting for HEREDOC

I have an easily reproducible error case for you, hope you dont mind 😄

With this input:

require 'set'

module Delegation
  class DelegationError < NoMethodError; end

  RUBY_RESERVED_KEYWORDS = %w[alias and BEGIN begin break case class def defined? do
                              else elsif END end ensure false for if in module next nil not or redo rescue retry
                              return self super then true undef unless until when while yield].freeze
  DELEGATION_RESERVED_KEYWORDS = %w[_ arg args block].freeze
  DELEGATION_RESERVED_METHOD_NAMES = Set.new(
    RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS
  ).freeze

  def delegate_missing_to(target)
    target = target.to_s
    target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target)

    module_eval <<-RUBY, __FILE__, __LINE__ + 1
      def respond_to_missing?(name, include_private = false)
        # It may look like an oversight, but we deliberately do not pass
        # +include_private+, because they do not get delegated.

        #{target}.respond_to?(name) || super
      end

      def method_missing(method, *args, &block)
        if #{target}.respond_to?(method)
          #{target}.public_send(method, *args, &block)
        else
          begin
            super
          rescue NoMethodError
            if #{target}.nil?
              raise DelegationError, "\#{method} delegated to #{target}, but #{target} is nil"
            else
              raise
            end
          end
        end
      end
    RUBY
  end
end

prettier-ruby creates syntactically incorrect output:

# frozen_string_literal: true

require 'set'

module Delegation
  class DelegationError < NoMethodError; end

  RUBY_RESERVED_KEYWORDS = %w[
    alias
    and
    BEGIN
    begin
    break
    case
    class
    def
    defined?
    do
    else
    elsif
    END
    end
    ensure
    false
    for
    if
    in
    module
    next
    nil
    not
    or
    redo
    rescue
    retry
    return
    self
    super
    then
    true
    undef
    unless
    until
    when
    while
    yield
  ]
    .freeze
  DELEGATION_RESERVED_KEYWORDS = %w[_ arg args block].freeze
  DELEGATION_RESERVED_METHOD_NAMES =
    Set.new(RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS).freeze

  def delegate_missing_to(target)
    target = target.to_s
    if DELEGATION_RESERVED_METHOD_NAMES.include?(target)
      target = "self.#{target}"
    end

    module_eval <<-RUBY
                      def respond_to_missing?(name, include_private = false)
        # It may look like an oversight, but we deliberately do not pass
        # +include_private+, because they do not get delegated.

        #{target}.respond_to?(name) || super
      end

      def method_missing(method, *args, &block)
        if #{target}.respond_to?(method)
          #{target}.public_send(method, *args, &block)
        else
          begin
            super
          rescue NoMethodError
            if #{target}.nil?
              raise DelegationError, "\#{method} delegated to #{target}, but #{target} is nil"
            else
              raise
            end
          end
        end
      end
    RUBY,
                __FILE__,
                __LINE__ + 1
  end
end

Prettier x Rubocop

Is there a way to pass styling rules to rubocop, the same way we pass prettier style to eslint in a .eslintrc file?

I want to be able to run rubocop in my CI (e.g. Travis) to check if files were indeed formatted by prettier.

Use case is a contributor not using prettier in his IDE; CI should fail.

created syntax error

thanks for this tool, awesome to have such a thing
Works really well it many many cases. I did run into this problem thou.
It changed

        if ENV['DEVELOPER_MODE']
          origins '*'
        else
          origins(/\Ahttps:\/\/.*\z/)
        end

into

        ENV['DEVELOPER_MODE'] ? origins '*' : origins(%r{\Ahttps:\/\/.*\z})

which is not valid ruby code (needs parens around the origins '*')

cheers

Long arguments don't get split properly on multiple lines and create invalid Ruby

Input

Hello.run 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', :test

Current output

Hello.run 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
:test,

This is actually invalid Ruby that produces a syntax error.

Expected output

Hello.run(
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  :test,
)

Invalid ruby code generated for begin statements

Input file

class Foo
=begin
hello world
=end

  def foo; end
end

Current output file

Generates code that's no longer valid:

class Foo
  =begin
hello world
=end

  def foo; end
end

Expected output file

The indentation of the begin block is left alone

class Foo
=begin
hello world
=end

  def foo; end
end

Crash on splat operator within array

Input file

[1, 2, 3, *foo]

Current output file

TypeError: path.call is not a function or its return value is not iterable

Expected output file

[1, 2, 3, *foo]

Publish on new name

For php we use @prettier/plugin-php
For ruby we can do same i think @prettier/plugin-ruby 👍

Also i think better change name to avoid misleading and save naming.

Long chains of method calls should be formatted one per line

Input

Person
  .select('people.id, people.name, comments.text')
  .joins(:comments)
  .where('comments.created_at > ?', 1.week.ago)

Current output

Person.select('people.id, people.name, comments.text').joins(:comments).where(
  'comments.created_at > ?', 1.week.ago
)

Expected output

Person
  .select('people.id, people.name, comments.text')
  .joins(:comments)
  .where('comments.created_at > ?', 1.week.ago)

or maybe

Person.select('people.id, people.name, comments.text')
      .joins(:comments)
      .where('comments.created_at > ?', 1.week.ago)

I’d be willing to help implement this change if we decide it’s a good idea, however I’d need a little guidance on how to go about doing that.

Crashing with comment and regex

Input file

This is the smallest program that I can get that crashes:

lines.each do |line|
  # comment
  assert_match!(/:\d+:in /, line)
end

Current output file

TypeError: path.call(...) is not a function or its return value is not iterable

Expected output file

lines.each do |line|
  # comment
  assert_match!(/:\d+:in /, line)
end

Crashes on predicate expression

Input file

user.name == "foo"

Current output file

Crashes:

TypeError: Cannot read property '0' of undefined

Expected output file

user.name == "foo"

Validate output file is valid Ruby code

Would it would make sense to run Ripper over the generated output file to ensure that it's still valid Ruby code? If it's not valid, then we'll leave the file as-is, and console.log the file path as being a failure.

I'm happy to do this if it seems worthwhile.

super without arguments

Input

def initialize
  super()
end

Current output

def initialize
  super
end

Expected output

def initialize
  super()
end

Crashes on class methodcall

Input file

SomeUtils::foo('hello world')

Current output file

TypeError: Cannot read property '0' of undefined

Expected output file

SomeUtils::foo('hello world')

Crash in print.js: Cannot read property '0' of undefined

Hello! I tried out the new Ruby plugin on one of @artsy's codebases (the PR is here; we're still collecting feedback on the formatting changes). I ran into a crash on a number of files:

The stack trace looks the same each time:

➜  ~/bin/exchange git:(prettier-ruby) ✗ ./node_modules/.bin/prettier --write --plugin=@prettier/plugin-ruby lib/order_shipping.rb
lib/order_shipping.rb
[error] lib/order_shipping.rb: TypeError: Cannot read property '0' of undefined
[error]     at Object.module.exports [as print] (/Users/ashfurrow/bin/exchange/node_modules/@prettier/plugin-ruby/src/print.js:29:11)
[error]     at callPluginPrintFunction (/Users/ashfurrow/bin/exchange/node_modules/prettier/bin-prettier.js:13590:18)
[error]     at /Users/ashfurrow/bin/exchange/node_modules/prettier/bin-prettier.js:13541:16
[error]     at Object.printComments (/Users/ashfurrow/bin/exchange/node_modules/prettier/bin-prettier.js:13264:17)
[error]     at printGenerically (/Users/ashfurrow/bin/exchange/node_modules/prettier/bin-prettier.js:13540:22)
[error]     at FastPath.call (/Users/ashfurrow/bin/exchange/node_modules/prettier/bin-prettier.js:13378:16)
[error]     at makeCall (/Users/ashfurrow/bin/exchange/node_modules/@prettier/plugin-ruby/src/utils.js:12:62)
[error]     at Object.call (/Users/ashfurrow/bin/exchange/node_modules/@prettier/plugin-ruby/src/nodes.js:208:32)
[error]     at Object.module.exports [as print] (/Users/ashfurrow/bin/exchange/node_modules/@prettier/plugin-ruby/src/print.js:8:32)
[error]     at callPluginPrintFunction (/Users/ashfurrow/bin/exchange/node_modules/prettier/bin-prettier.js:13590:18)

Steps to reproduce:

  • Install the plugin as described in the readme (this occurred on @prettier/plugin-ruby version 0.3.2 and prettier version 1.16.4).
  • Try running ./node_modules/.bin/prettier --write --plugin=@prettier/plugin-ruby, passing in a path to one of the files linked to above.

You'll see a crash with the above stack trace. Let me know what other information I can provide, and thank you for your work on this tool!

Convert parallel assignment (massign) expressions into multiple assignment expressions

Currently, when @prettier/plugin-ruby encounters an massign expression, it will always print it out as an massign. However, there are one case where we don't want to do that:

a, b, c = 1, 2, 3

This is functionally equivalent to:

a = 1
b = 2
c = 3

We should handle this inside the massign handler in src/nodes.js by checking if the number of args on the left is equal to the number of args on the right, that none of them have parens around them, and that none of them are splats. If these conditions are met, the massign expression should be converted into multiple individual assignments.

I'd be happy to pair with someone to accomplish this. It shouldn't take too long once you get the hang of how nodes are being printed.

Comments disappear

Input file

# frozen_string_literal: true

module Foo
  # Hello
  # world
  # comments
  # disappear
  #
  def foo
  end
end

Current output file

The comments attached to foo disappear

# frozen_string_literal: true

module Foo
  #

  def foo; end
end

Expected output file

# frozen_string_literal: true

module Foo
  # Hello
  # world
  # comments
  # disappear
  #
  def foo; end
end

Better heredoc handling

Input file

def sql
  <<-SQL
    SELECT *
    FROM foo
  SQL
end

Current output file

def sql
'    SELECT *
     FROM foo
'
end

Expected output file

def sql
  <<-SQL
    SELECT *
    FROM foo
  SQL
end

Does not handle empty do end

Input

RSpec.describe SomeCoolClass do
end

Current output

RSpec.describe SomeCoolClass {  }

Expected output

RSpec.describe SomeCoolClass do
end

Thanks so much this is such an awesome project! I've been wanting this ever since I started using prettier. You rock!

Crashes on or statement with initializer call

Input file

logger = options[:logger] || Logger.new

Current output file

Crashes:

TypeError: Cannot read property '0' of undefined

Expected output file

logger = options[:logger] || Logger.new

Method keyword argument lists run on

Metadata

  • Ruby version: 2.5.1
  • @prettier/plugin-ruby version: 0.6.1

Input

  def initialize(
    database_setup: nil, subscription_setup: nil, board_setup:, prefix:, member_id: nil, board_id: nil, org_id: nil, board_last_activity_at: nil
  )
    1
  end

Current output

  def initialize(
    database_setup: nil, subscription_setup: nil, board_setup:, prefix:, member_id: nil, board_id: nil, org_id: nil, board_last_activity_at: nil
  )
    1
  end

Expected output

  def initialize(
    database_setup: nil,
    subscription_setup: nil,
    board_setup:,
    prefix:,
    member_id: nil,
    board_id: nil,
    org_id: nil,
    board_last_activity_at: nil
  )
    1
  end

Gracefully handle more Ruby versions other than 2.6

When running with Ruby 2.6 everything seems well, but with Ruby 2.5 it crashes:

app/helpers/application_helper.rb[error] app/helpers/application_helper.rb: TypeError: Cannot read property '0' of undefined
[error]     at Object.module.exports [as print] (/users/foo/Documents/code/test-app/node_modules/prettier-plugin-ruby/src/print.js:16:11)
[error]     at callPluginPrintFunction (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13590:18)
[error]     at /users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13541:16
[error]     at Object.printComments (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13264:17)
[error]     at printGenerically (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13540:22)
[error]     at FastPath.call (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13378:16)
[error]     at Object.call (/users/foo/Documents/code/test-app/node_modules/prettier-plugin-ruby/src/nodes.js:208:12)
[error]     at Object.module.exports [as print] (/users/foo/Documents/code/test-app/node_modules/prettier-plugin-ruby/src/print.js:8:32)
[error]     at callPluginPrintFunction (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13590:18)
[error]     at /users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13541:16
app/helpers/blog_helper.rb[error] app/helpers/blog_helper.rb: TypeError: Cannot read property '0' of undefined
[error]     at Object.module.exports [as print] (/users/foo/Documents/code/test-app/node_modules/prettier-plugin-ruby/src/print.js:16:11)
[error]     at callPluginPrintFunction (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13590:18)
[error]     at /users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13541:16
[error]     at Object.printComments (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13264:17)
[error]     at printGenerically (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13540:22)
[error]     at FastPath.call (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13378:16)
[error]     at Object.call (/users/foo/Documents/code/test-app/node_modules/prettier-plugin-ruby/src/nodes.js:208:12)
[error]     at Object.module.exports [as print] (/users/foo/Documents/code/test-app/node_modules/prettier-plugin-ruby/src/print.js:8:32)
[error]     at callPluginPrintFunction (/users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13590:18)
[error]     at /users/foo/Documents/code/test-app/node_modules/prettier/bin-prettier.js:13541:16

Comment handling on arrays

Prettier doesn't seem to handle the scenario of comments on arrays

Input file

[
  # Foo bar
  "hello world"
]

Current output file

Crashes:

TypeError: path.call(...) is not a function or its return value is not iterable

Expected output file

[
  # Foo bar
  "hello world"
]

Convert empty case expressions into if expressions

Currently, when @prettier/plugin-ruby encounters a case expression, it will always print it out as a case. However, there are one case where we don't want to do that:

case
when foo
  ...
when bar
  ...
end

This is functionally equivalent to:

if foo
  ...
elsif bar
  ...
end

We should handle this inside the case handler in src/nodes.js by checking if the case expression contains a predicate, and if it doesn't then switching to printing out and if/elsif block. This will also involve using getParentNode from within the when to check if the case expression has a predicate to know whether or not to print the "when" keyword or the "elsif" keyword.

I'd be happy to pair with someone to accomplish this. It shouldn't take too long once you get the hang of how nodes are being printed.

TypeError: Cannot read property 'toString' of null

I have a bunch of "seed" files that populate development and test dbs. One file in particular has about 550 seed lines, each about 2k characters long (inline maps with string keys, hash rockets, and values).

If I run prettier over it, it errors with:

[error] db/seeds/categories.seeds.rb: TypeError: Cannot read property 'toString' of null
[error]     at Object.module.exports [as parse] (/Users/noah/dev/ebth-com/node_modules/@prettier/plugin-ruby/src/parse.js:7:30)
[error]     at Object.parse$2 [as parse] (/Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:10641:19)
[error]     at coreFormat (/Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:13858:23)
[error]     at format (/Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:14117:73)
[error]     at formatWithCursor (/Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:14133:12)
[error]     at Object.formatWithCursor (/Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:42401:15)
[error]     at format$1 (/Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:43770:21)
[error]     at /Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:43965:16
[error]     at /Users/noah/dev/ebth-com/node_modules/prettier/bin-prettier.js:43905:14
[error]     at Array.forEach (<anonymous>)

If I cut it up at all (in an attempt to binary-search which lines it chokes on), prettier returns correct file, which makes me think it's about the size of the hashes or the size of the call and not something inside the hash.

Error in lambda creation: in 'lambda': tried to create Proc object without a block (ArgumentError)

Input

scope :sorted, ->  { order("#{table_name}.priority desc, #{table_name}.sort_order ASC, #{table_name}.name asc") }

Current output

scope :sorted,
      lambda do
        order(
          "#{table_name}.priority desc, #{table_name}.sort_order ASC, #{table_name}.name asc"
        )
      end

Running rails s generates this error: app/models/temp.rb:252:in 'lambda': tried to create Proc object without a block (ArgumentError)

Expected output

scope :sorted,
      (lambda do
        order(
          "#{table_name}.priority desc, #{table_name}.sort_order ASC, #{table_name}.name asc"
        )
      end)

Or maybe (tho this gets Rubocop yelling at me):

scope :sorted,
      -> {
        order(
          "#{table_name}.priority desc, #{table_name}.sort_order ASC, #{table_name}.name asc"
        )
      }

This also affect when a Proc in a has_many with traits afterwards:

has_many :staff, -> { where(staff_type: 2, users: { role: User::STAFF } ) }, through: users

becomes

has_many :staff,
         lambda do
           where(
             staff_type: 2, users: { role: User::STAFF }
           )
         end,
         through: :users

which returns (when run):
app/models/temp.rb:221: syntax error, unexpected ',', expecting keyword_end (SyntaxError)

Better inline comment support

At the moment, there are 3 types of comments, all handled somewhat differently.

  • @start_comments - these are comments that go at the very beginning of the file before any code. To my knowledge these are working correctly atm. An example would be:
# this is a start comment

def foo; end
  • @begin_comments - these are comments that are the first statement within a block. To my knowledge these are working correctly atm. Examples are:
class Foo
  # comment
  abc
end

module Foo
  # comment
  abc
end

def foo
  # comment
  abc
end

Note that this does result in some odd spacing within the class and module nodes. More investigation is needed here.

  • @end_comment - these are inline comments. They are currently parsed in all kinds of different ways depending on lexer state. Sometimes they work, and sometimes they don't. Definitely more investigation is needed into this. These are the ones that are handled by src/print.js. An example is:
foobar # comment

Running prettier twice on the same file crashes

Input

https://github.com/rails/rails/blob/9099d66bc38f2e560613258f520d46df624d99c0/activesupport/lib/active_support/configurable.rb

Current output

       # Compiles reader methods so we don't have to go through method_missing.
       def self.compile_methods!(keys)
         keys.reject { |m| method_defined?(m) }.each do |key|
-          class_eval <<-RUBY, __FILE__, __LINE__ + 1
-            def #{key}; _get(#{key.inspect}); end
-          RUBY
+          class_eval <<-RUBY
+                                 def #{key}; _get(#{key
+                       .inspect}); end
+          RUBY,
+                     __FILE__,
+                     __LINE__ + 1
         end
       end
     end

Note that this code crashes when running prettier again on the same file:

src/ripper.rb:33:in block in parse': undefined method []' for nil:NilClass (NoMethodError)

Expected output

Not to crash

Reproduction

Run prettier with --write twice on the Rail's file, or once with --debug-check

yarn prettier --debug-check --plugin=. --parser=ruby ../rails/activesupport/lib/active_support/configurable.rb

Document how to set config

I'm sure I'm just missing something, but I cannot find any documentation on how to set the config variables when running from the command line. No prettier plugin I can find documents that and prettier itself doesn't seem to document it. Is it possible, or am I forced to use the defaults if I use the command line?

Ternary handling edge cases

Input file

if foo

else
  do_something
end

Current output file

foo ?  : do_something

Expected output file

if foo

else
  do_something
end

Properly escape double quotes

Input

When using preferSingleQuotes: false

str = 'I want to say "Hello world"'

Current output

str = "I want to say "Hello world""

Expected output

str = "I want to say \"Hello world\""

Thanks for this plugin. I use javascript & ruby and every time I write in ruby I miss prettier!

Invalid generation for do block conversion

Input file

property :message do
  key :type, :string
end

Current output file

Invalid Ruby code is generated:

property :message { key :type, :string }

Expected output file

property(:message) { key :type, :string }

Comment on break results in crash

Input file

loop do
    if foo?
      break # comment
    end
  end
end

Current output file

Cannot destructure property `parts` of 'undefined' or 'null'

Expected output file

loop do
    if foo?
      break # comment
    end
  end
end

Comment handling on hashes

Prettier doesn't seem to handle the scenario of comments on hashes

Input file

{
  # Foo bar
  hello: "world"
}

Current output file

Crashes:

TypeError: path.call(...) is not a function or its return value is not iterable

Expected output file

{
  # Foo bar
  hello: "world"
}

Heredoc Interpolation Containing Strings

Heredocs containing interpolation blocks that themselves contain strings seem to cause an error in ripper.rb.

Input

Bare-bones fail case:

<<~HERE
  This is a squiggly heredoc with interpolation containing a string!
  #{""}
HERE

Slightly more realistic, tho still maybe not well factored:

foo = "bar"
<<~HERE
  This is a squiggly heredoc with interpolation containing a string!
  #{foo.gsub("r", "z")}
HERE

Current output

[error] heredoc.rb: Error: /workspace/test/node_modules/prettier-plugin-ruby/src/ripper.rb:158:in `on_string_literal': undefined method `[]' for nil:NilClass (NoMethodError)
[error]         from /workspace/test/node_modules/prettier-plugin-ruby/src/ripper.rb:28:in `parse'
[error]         from /workspace/test/node_modules/prettier-plugin-ruby/src/ripper.rb:28:in `parse'
[error]         from /workspace/test/node_modules/prettier-plugin-ruby/src/ripper.rb:207:in `<main>'
[error] 
[error]     at Object.module.exports [as parse] (/workspace/test/node_modules/prettier-plugin-ruby/src/parse.js:9:11)
[error]     at Object.parse$2 [as parse] (/workspace/test/node_modules/prettier/bin-prettier.js:10641:19)
[error]     at coreFormat (/workspace/test/node_modules/prettier/bin-prettier.js:13858:23)
[error]     at format (/workspace/test/node_modules/prettier/bin-prettier.js:14117:73)
[error]     at formatWithCursor (/workspace/test/node_modules/prettier/bin-prettier.js:14133:12)
[error]     at Object.formatWithCursor (/workspace/test/node_modules/prettier/bin-prettier.js:42401:15)
[error]     at format$1 (/workspace/test/node_modules/prettier/bin-prettier.js:43770:21)
[error]     at /workspace/test/node_modules/prettier/bin-prettier.js:43965:16
[error]     at /workspace/test/node_modules/prettier/bin-prettier.js:43905:14
[error]     at Array.forEach (<anonymous>)

Expected output

<<~HERE
  This is a squiggly heredoc with interpolation containing a string!
  #{''}
HERE

or

<<~HERE
  This is a squiggly heredoc with interpolation containing a string!
  
HERE

Slightly more realistic, tho still maybe not well factored:

foo = "bar"
<<~HERE
  This is a squiggly heredoc with interpolation containing a string!
  #{foo.gsub('r', 'z')}
HERE

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.