1 class RunLogEntry # < ActiveRecord::Base # we don't want to be a database model 2 3 # if we were a databse model, the following accessors would be generated based on 4 # the table schema. But since we're not, we get to do them ourselves, along with 5 # a constructor, and a model method which shows us average speed. 6 7 # attr_accessor is a class method which uses generates access methods for attributes. 8 # you can add your own attribute methods with the names #foo and #foo= for getters and 9 # setters respectively. #foo can just be called by 'myObject.foo', which makes it look 10 # just like a field, and #foo= is called whenever the 'field' foo is assigned to, eg. 11 # 'myObject.foo = "blah"'. Hence, accessors make the methods look like fields, but still 12 # conform to the "only allow accss through methods" OO principle. 13 attr_accessor :time, :distance, :date 14 15 def initialize(time, distance, date) 16 # instance variables don't have to be declared (created on first use) and start with a 17 # single atse (@ivar). class variables (static in Java) also aren't declared, and start with 18 # double atses (@@cvar). all variables are inheritly private - you can only access things 19 # through methods, which is why the attr_* helper class methods exist 20 @time, @distance, @date = time, distance, date 21 end 22 23 def average_speed 24 # return values just fall out the end of a method - if there is no return statement, then 25 # the return value of a method is just the last value computed 26 @distance / @time 27 end 28 end