17

编辑了这个旧问题以包含下面的答案: Rubocop 有它https://github.com/rubocop-hq/rails-style-guide#macro-style-methods

Rails 是关于“约定优于配置”的。但是,我还没有遇到 Rails 模型中关联、范围、包含、验证等顺序的“标准”。以以下简化的产品模型为例:

class Product < ActiveRecord::Base
  mount_uploader :logo, AssetUploader
  acts_as_taggable
  paginates_per 50

  include ActionView::Helpers::NumberHelper

  belongs_to :company

  validates_presence_of [:title, :price, :plu]

  scope :on_website, where(display: true)

  def display_price
    ...
  end
end

这是正确的顺序吗?这对很多人来说可能并不那么重要,但我个人认为,如果有一个关于这个的约定会很棒。

4

2 回答 2

10

没有这样的约定。但是您可以为您的项目创建一个并在所有模型中保持一致。这就是我所遵循的。

class Model < ActiveRecord::Base
   #all mixins
   include Something
   extend Something

   #other stuff
   acts_as_taggable
   paginates

   #associations
   has_many :something
   belongs_to :something_else

   #validations
   validate_presence_of :something

   #scopes
   scope :something

   #instance methods
   def instance_method
   end

   #class methods
   def self.method
   end

   #private methods
   private
   def method2
   end
end
于 2013-06-06T16:32:24.763 回答
8

Rubocop 有它 https://github.com/rubocop-hq/rails-style-guide#macro-style-methods

class User < ActiveRecord::Base
  # keep the default scope first (if any)
  default_scope { where(active: true) }

  # constants come up next
  COLORS = %w(red green blue)

  # afterwards we put attr related macros
  attr_accessor :formatted_date_of_birth

  attr_accessible :login, :first_name, :last_name, :email, :password

  # Rails 4+ enums after attr macros
  enum gender: { female: 0, male: 1 }

  # followed by association macros
  belongs_to :country

  has_many :authentications, dependent: :destroy

  # and validation macros
  validates :email, presence: true
  validates :username, presence: true
  validates :username, uniqueness: { case_sensitive: false }
  validates :username, format: { with: /\A[A-Za-z][A-Za-z0-9._-]{2,19}\z/ }
  validates :password, format: { with: /\A\S{8,128}\z/, allow_nil: true }

  # next we have callbacks
  before_save :cook
  before_save :update_username_lower

  # other macros (like devise's) should be placed after the callbacks

  ...
end
于 2019-09-04T01:52:05.677 回答