Search code examples
rubycoding-stylereadabilityhuman-readable

Improve readability of large attr_accessor


What should I do when defining constants or attr_accessor symbols that are very large? For example, something like this:

ATTRIBUTES = %w(id name full_name owner private html_url description fork url forks_url keys_url collaborators_url teams_url hooks_url issue_events_url events_url assignees_url branches_url tags_url blobs_url git_tags_url git_refs_url trees_url statuses_url languages_url stargazers_url contributors_url subscribers_url subscription_url commits_url git_commits_url comments_url issue_comment_url contents_url compare_url merges_url archive_url downloads_url issues_url pulls_url milestones_url)

attr_accessor :name, :login, :full_name, :owner, :private, :html_url, :description, :fork, :url

in a class is terrible. Is this the best way? I want to know if there are other ways just to improve readability.


Solution

  • Change lines at certain width:

    ATTRIBUTES = %w[
      id name full_name owner private html_url description fork url forks_url
      keys_url collaborators_url teams_url hooks_url issue_events_url events_url
      ...
    ]
    

    or if you do not need to save lines, then putting each item on a separate line may be easy:

    ATTRIBUTES = %w[
      id name
      full_name
      owner
      private
      html_url
      ...
    ]
    

    or if you have time formatting, then you might want to make several columns and align them:

    ATTRIBUTES = %w[
      id                 name                full_name          owner             
      private html_url   description fork    url                forks_url
      keys_url           collaborators_url   teams_url          hooks_url
      issue_events_url   events_url          ...
    ]
    

    In Ruby 2.0, a new literal expression %i[...] was introduced for array of symbols:

    attr_accessor *%i[
      name
      login
      full_name
      owner
      private
      ...
    ]