Forum: Ruby on Rails Newbie problem with adding new method to a class

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Szymon N. (Guest)
on 2006-03-06 22:32
Hi!

If i have Image class and i'd like to add 'create_thumbnail' method to
it, which will later be called from product controller, where to put
this method and how to call it?

I've tried putting it inside image controller and image model, then call
it like Image.create_thumbnail, but it didn't work - undefined method
`create_thumbnail' for Image:Class.
Jules J. (Guest)
on 2006-03-06 22:49
(Received via mailing list)
If this is an activerecord model, the create method is probably there:

Image.create(:someattribute => 'value')

But if you want to define your own:

class Image
  def self.create
    'hi'
  end
end

>> Image.create
=> 'hi'

On Monday, March 06, 2006, at 9:32 PM, szymek wrote:
>--
>Posted via http://www.ruby-forum.com/.
>_______________________________________________
>Rails mailing list
>removed_email_address@domain.invalid
>http://lists.rubyonrails.org/mailman/listinfo/rails


Jules
Jeff C. (Guest)
on 2006-03-06 23:02
szymek  wrote:
> Hi!
>
> If i have Image class and i'd like to add 'create_thumbnail' method to
> it, which will later be called from product controller, where to put
> this method and how to call it?
>
> I've tried putting it inside image controller and image model, then call
> it like Image.create_thumbnail, but it didn't work - undefined method
> `create_thumbnail' for Image:Class.

Do you want a class method or an instance method?

Class methods look like this:

class Image

  def self.create_thumbnail
    # return a thumbnail image here
    # You probably need to pass some arguments to this method
    # so it knows what to do
  end

end

but instance methods look like this:

class Image

  def create_thumbnail
    # return a thumbnail image of this object
  end

end

Notice there's no "self." prefixed to the method name here.

Jeff
www.softiesonrails.com
Szymon N. (Guest)
on 2006-03-07 00:06
Thanks a lot for clearing things up!
Anthony G. (Guest)
on 2006-03-07 09:48
> Do you want a class method or an instance method?

Which is most appropriate ?

Class methods can be used without being tied to any particular object.

Instance methods belong to a individual object.


_tony
This topic is locked and can not be replied to.