Created
April 5, 2012 10:53
-
-
Save pifleo/2309931 to your computer and use it in GitHub Desktop.
Rails - models organization - Keep code structure in models consistent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Keep code struture in models consistent | |
# Inspired by http://rails-bestpractices.com/posts/75-keep-code-struture-in-models-consistent | |
# One example: (From top to bottom) | |
associations | |
scopes | |
class methods | |
validates | |
callbacks | |
instance methods | |
# And for models annotation | |
# http://rails-bestpractices.com/posts/68-annotate-your-models | |
$ gem install annotate | |
$ annotate --exclude tests,fixtures |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
# == Schema Information | |
# | |
# Table name: users | |
# | |
# id :integer not null, primary key | |
# ... | |
# | |
class User < ActiveRecord::Base | |
## 0. MODEL EXTENSIONS | |
# - includes / extends | |
include DeviseByLogin # lib/devise_by_login.rb | |
# - Gems | |
acts_as_follower # https://github.com/tcocca/acts_as_follower | |
# - serialized attributes | |
store :preferences, accessors: [ :dont_send_email ] | |
## 1. ASSOCIATIONS / ATTRIBUTES | |
belongs_to :... | |
has_one :profile, :dependent => :destroy | |
has_many :... | |
has_and_belongs_to_many :... | |
accepts_nested_attributes_for :profile, :allow_destroy => true | |
# - attr_accessible | |
attr_accessible :username, ... | |
attr_protected :... | |
attr_accessor :... | |
## 2. SCOPES | |
scope :confirmed, where('confirmed_at IS NOT NULL') | |
## 3. CLASS METHODS | |
class << self | |
end | |
## 4. VALIDATES | |
validates :terms_of_service, :acceptance => true, :on => :create | |
validates :password, :presence => true, | |
:confirmation => true, | |
:length => { :minimum => 6 }, | |
:on => :create | |
validates :username, :uniqueness => { :case_sensitive => false }, :if => :username? | |
## 5. CALLBACKS | |
after_create :set_default_data | |
## 6. INSTANCE METHODS | |
# - first attributes formatting | |
def to_s | |
self.name | |
end | |
# - others methods | |
# - then private | |
private | |
def set_default_data | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment