Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 507
stevec Avatar asked Nov 18 '25 04:11

stevec


1 Answers

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
like image 191
spickermann Avatar answered Nov 19 '25 21:11

spickermann