Chaining your own method in Ruby on Rails
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_met开发者_Go百科hod(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.
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.
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.
精彩评论