Skip to content

Instantly share code, notes, and snippets.

@unixmonkey
Last active September 3, 2020 12:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unixmonkey/391373 to your computer and use it in GitHub Desktop.
Save unixmonkey/391373 to your computer and use it in GitHub Desktop.
Example Rails model with all the bells and whistles
# == Schema Information
#
# Table name: flying_spaghetti_monsters
#
# id :integer(4) not null, primary key
# awesomeness :string
# meatballs :boolean
# last_seen :datetime
# model-specific requires
require 'foo'
class FlyingSpaghettiMonster < ActiveRecord::Base
# includes & plugin declarations
include AwesomeSauce
acts_as_omnicient
# class variables & constants
PANT_SIZES = %w(Small Medium Large Humongaginormous)
@@per_page = 10
# accessors & readers
attr_accessible :awesomeness
# before/after/around filters
before_create :set_initial_awesomeness
# relationships
has_one :all_seeing_eye
has_many :noodly_appendages
belongs_to :dimension
accepts_nested_attributes_for :noodly_appendages
# validations
validates_presence_of :meatballs
# named scopes
scope :recently_spotted, -> { :conditions => ['last_seen >=', 1.month.ago] }
# class methods
def self.email_worshippers
emails = worshippers.all.collect(&:email)
WorshipperMailer.newsletter_to(emails).deliver
end
# virtual attribute definitions
def genus
"flagamorphicus #{awesomeness}ica"
end
def supa_awesome?
awesome == 'supa'
end
# instance methods
def appendage_count
appendages.count
end
def add_appendage
appendage.create!(:flying_spaghetti_monster_id => id, :size => 'monsterous')
end
# defined getters & setters
def per_page
@@per_page
end
def per_page=(num)
@@per_page = (num + 1)
end
# protected methods
protected
def worshipper_names
worshippers.all.collect(&:name)
end
# private methods
private
def set_initial_awesomeness
awesomeness = 'semi-awesome'
end
end
__END__
Unstructured heredoc text or template
Seriously, don't use this unless you
are doing some fancy single-file app
or something
@unixmonkey
Copy link
Author

Group class variables and constants together and move up closer to the top.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment