dev wrote:
> For some reason I am tripping up on the use of self and new.
> 
> class LineItem < ActiveRecord::Base
>   belongs_to :order
>   belongs_to :product
> 
>   def self.from_cart_item(cart_item)
>     li = self.new
>     li.product = cart_item.product
>     li.quantity = cart_item.quantity
>     li.total_price = cart_item.price
>     li
>   end
> end

This pattern looks very much like the NSCoding protocol pattern that I'm 
familiar with from the Cocoa frameworks. Compare what you have with this 
Objective-C example:

- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    mapName = [[coder decodeObjectForKey:@"MVMapName"] retain];
    legendView = [[coder decodeObjectForKey:@"MVLegend"] retain];
    auxiliaryView = [coder decodeObjectForKey:@"MVAuxView"];
    magnification = [coder decodeFloatForKey:@"MVMagnification"];
    return self;
}

This implementation is slightly more abstract, and implemented as an 
instance method rather than a class method, but it serves essentially 
the same purpose.

To use this method you would do this:
id myObject = [[MyObject alloc] initWithCoder:coder];

Notice that Obj-C instance methods begin with a minus sign (-) and class 
methods begin with a plus sign (+). Since this is an instance method the 
instance must be allocated before being initialized. This alloc-init 
process is roughly equivalent to Ruby's "new" method.

One way to declare a class method in Ruby is to begin it with "self." 
Which is what you are doing in your code (self.from_cart_item). In order 
to use class methods you send messages to the class rather than an 
instance of the class:

my_line_item = LineItem.from_cart_item # LineItem class is the receiver 
of message from_cart_item
-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to