class Account
attr_accessor :balance
def initialize(balance)
self.balance = balance
end
def interest
end
end
class SavingsAccount < Account
def interest
balance * 0.06
end
end
class CheckingAccount < Account
def interest
balance * 0.01
end
end
$ a = []
$ a << SavingsAccount.new(10000)
$ a << CheckingAccount.new(2500)
$ a.inject(0) {|total_interest, account| total_interest += account.interest}
class Document
include ActiveModel::Conversion
end
class Video
include ActiveModel::Conversion
end
class Audio
include ActiveModel::Conversion
end
content = [Document.new, Video.new, Audio.new]
puts content.to_json
def do_stuff(cool_beans)
puts cool_beans
end
def do_stuff(cool_beans, cool_bannans = nil)
puts cool_beans
puts cool_bannans if cool_beans
end
puts "this is" + " overloaded"
=> "This is overloaded"
1 + 2 + 3
=> 6
class Fixnum
def +(arg)
self - arg
end
end
1 + 2 + 3
=> -4
Rails Guides Polymorphic Associations
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
belongs_to :user
end
class Artical < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Product < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class User < ActiveRecord::Base
has_many :comments
has_many :acticles, :through => :comments, :source => :commentable, :source_type => 'Article'
end