Skip to content

Transform Phlex code output through RuboCop or SyntaxTree #59

@marcoroth

Description

@marcoroth

Let's say we have this:

<%= tag.div class: something? ? "class-1" : "class-2" do %>
  <%= content_tag :span, something.text %>
<% end %>

Which would generate this through phlexing today:

class SomethingComponent < Phlex::HTML
  include Phlex::Rails::Helpers::ContentTag
  include Phlex::Rails::Helpers::Tag

  attr_accessor :something

  def initialize(something:)
    @something = something
  end

  def template
    tag.div class: something? ? "class-1" : "class-2" do
      content_tag :span, something.text
    end
  end

  private

  def something?(*args, **kwargs)
    # TODO: Implement me
  end
end

But since this is a regular Ruby class now we could write any RuboCop rule (or maybe even a SyntaxTree mutation visitor) which statically analyses the code and auto-fixes it (we could even make the rules toggleable from the UI)

For example some rules could be:

  • rewrite tag.div as div { ... }
  • rewrite content_tag :span to span { ... }
  • rewrite all references of something inside def template to @something and remove the attr_accessor for it
  • rewrite class: something? ? "class-1" : "class-2" to **classes(something?: { then: "class-1", else: "class-2" })
  • ...

We could even release these rules standalone as rubocop-phlex which people could use in their project independent of phlexing

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions