Reputation: 3870
I am new to rails and am figuring out the best ways to write certain methods.
I am trying to write a method that belongs to a certain model and can be accessed without initiating an instance. So far I have this under my class PaymentNotification < ActiveRecord::Base
def url
url_for(:controller => 'payment_notifications', :only_path => false)
end
The problem here is that I need to do this to access the url
n = PaymentNotification.new
n.url
In my code, I want to be able to write PaymentNotification.url to access the method relevant to that model.
Maybe I am thinking about this the wrong way and someone can guide me. Basically, what I am trying to achieve is that each model can have its set of methods and attributes so that they all are organized and I know from the code which file each method is declared in, instead of just calling a
payment_notification_url
which may be located in any of the irrelevant initialization files. I saw helper methods but it seems like i still won't be able to use a dot syntax and will have to write something like "payment_notification_url" to access my url
Any ideas on the best way to go about doing this?
Upvotes: 0
Views: 1558
Reputation: 84140
You need to define a class method via the self keyword.
def self.url
url_for(:controller => 'payment_notifications', :only_path => false)
end
Then you can use PaymentNotification.url
class A
def self.a
p "Class method"
end
def b
p "Instance Method"
end
end
A.a #Class method
#A.b #NoMethodError
a = A.new
a.b #Instance Method
#a.a #NoMethodError
Upvotes: 1