stevec
stevec

Reputation: 52238

How to make a custom method that can be used anywhere in rails app

I wish to make a custom method (e.g. def plus_two(x) x + 2 end and have it be accessible everywhere within the app - that is, accessible in the controller, model, console, views, tests, and any other .rb files. I currently have the same method defined in many areas of the app, and wish to make it DRY

How can this be achieved?

Note: I don't mind if calling the method requires prepending something (I have seen some answers where methods are prepended with :: or with a namespace, but otherwise have a preference to keep code succinct where possible

I have done some reading at similar questions (e.g. this one) but I can't quite get it

Upvotes: 3

Views: 1191

Answers (1)

spickermann
spickermann

Reputation: 106792

Reading the comments it seems like you are just looking for a clear and simple example of a method that is available everywhere in your application:

# in app/models/calculator.rb
module Calculator
  def self.plus_two(x) 
    x + 2 
  end
end

Which can be called like this:

Calculator.plus_two(8)
#=> 10

Upvotes: 6

Related Questions