Created
October 27, 2010 15:32
-
-
Save ingemar/649270 to your computer and use it in GitHub Desktop.
How to structure a ruby class
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
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