Skip to content

Instantly share code, notes, and snippets.

@ingemar
Created October 27, 2010 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ingemar/649270 to your computer and use it in GitHub Desktop.
Save ingemar/649270 to your computer and use it in GitHub Desktop.
How to structure a ruby class
require 'open-magazine' # requirements
class Article
include Any::Aweseome::Module # includes and extensions
belongs_to :author # relations to other models
attr_accessor :title, :pages # attribute definitions
RESERVED_TITLES = ['Coding Ruby'] # constants...
attr_accessible :title # ActiveRecord mass-assignment white-list and
# other security related settings
scope :large, where(:pages.lg => 300) # class method macros like finders etc
mount_uploader :cover_image, CoverImageUploader
validates_presence_of :title # validations
# put callbacks & hooks before any methods
# it's important to be aware of them
# since they are automagical
before_save :calculate_price
after_create :bill_book_stores
# put class methods first...
def self.dust_books
all.each(&:dust!)
end
# then instance methods
# prioritize setter methods above others - they are unexpected
def title=(str)
@title = str.strip.downcase
end
# other methods
def nice_title
title.titleize
end
# query methods
def best_seller?
Author.awarded.include?(author.name)
end
# private & protected methods
private
def bill_book_stores
Billing.create(self)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment