Skip to content

Instantly share code, notes, and snippets.

@getadeo
Created September 25, 2019 03:59
Show Gist options
  • Select an option

  • Save getadeo/b6cffd8b9ccb169a058c92c577adbf30 to your computer and use it in GitHub Desktop.

Select an option

Save getadeo/b6cffd8b9ccb169a058c92c577adbf30 to your computer and use it in GitHub Desktop.

Revisions

  1. Genesis Tadeo created this gist Sep 25, 2019.
    85 changes: 85 additions & 0 deletions gtoup-macro-style-methods.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,85 @@
    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

    has_many :through

    Prefer has_many :through to has_and_belongs_to_many. Using has_many :through allows additional attributes and validations on the join model.

    # not so good - using has_and_belongs_to_many

    class User < ActiveRecord::Base

    has_and_belongs_to_many :groups

    end

    class Group < ActiveRecord::Base

    has_and_belongs_to_many :users

    end

    # preferred way - using has_many :through

    class User < ActiveRecord::Base

    has_many :memberships

    has_many :groups, through: :memberships

    end

    class Membership < ActiveRecord::Base

    belongs_to :user

    belongs_to :group

    end