Newbie problem with adding new method to a class


#1

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.


#2

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


#3

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


#4

Thanks a lot for clearing things up!


#5

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