views:

21

answers:

2

In my Rails app, I am used to using syntax like the following in a number of places, including helpers/application_helper.rb:

def my_method(x,y)
  return x+y
end

I am also used to calling the resulting method from basically anywhere in my app using syntax like this:

my_method(2,3)

However, I'd like to be able to use syntax like like this:

class_from_my_rails_app.my_method(3)

How and where do I define my_method so I can use it like this?

I'm happy to consult the documentation, but I just don't know what the latter style is called. What do you call it?

Many thanks,

Steven.

+1  A: 

I think you're talking about creating a class method.

class MyClass
  def self.my_method(x,y)
    return x+y
  end
end

This allows you to call

MyClass.my_method(2,3)

This probably belongs in a model class, rather than a helper class, rails-wise.

Michael Forrest
Thanks. I was imagining more new_instance = MyClass.new then new_instance.my_method where at least one of x and Y come from new_instance rather than being fed in via parentheses. If that makes sense? Much as if I had invented "truncate" in my_string.truncate(20), which grabs "text" from my_string but other arguments from the parentheses.
steven_noble
A: 

THe thing you want to create is called an instance method. Implemented as follows:

class YourClass

  def initalize(x)
    @x =x
  end

  def do_something(y)
    @x + y
  end

end

which you would use a follows:

my_class = YourClass.new(20)

puts my_class.do_something(10)
=> 30

But actually this is so fundamental to object oriented programming and ruby that i am surprised to even see this question.

I would suggest reading up on ruby as a language, a very good book t get you started is The Well-grounded Rubyist, that starts from all the basics and works it's way up into all the details.

I hope this helps. If i misunderstood your question, i apologise, and would be glad to elaborate on any part.

nathanvda
Thanks. That's exactly what I was looking for. I'll check out the book too, and hopefully this will continue to be a place where those of us who are newish to Rails can still search for answers as we reach backwards into the underlying Ruby fundamentals.
steven_noble
Glad to have been of help.
nathanvda