Reputation: 541
I have multiple classes (4-5) using same constant value, say PI = 3.14. What is the best way to define that constant at one place in Ruby and in RoR application?
Do I construct one module with given Constant and include in all the classes that are using it?
What are best practices and standard Ruby or RoR way?
Upvotes: 1
Views: 2775
Reputation: 31
All your application classes shall be under a namespace, given MyApp
.
So all shared constants could be declared in the MyApp
module :
module MyApp
APP_CONST_1 = 42
APP_CONST_2 = 3.14
# ...
end
class MyApp::User
def the_answer
MyApp::APP_CONST_1 # 42
end
end
Upvotes: 2
Reputation: 230286
Instead of including this constant everywhere, you could just define it in one place and then refer that directly
# config/initializers/constants.rb, for example.
module Constants
PI = 3.1415926535897932384626433832795028841971
end
# app/models/circle.rb
class Circle
attr_reader :radius
def area
Constants::PI * radius ** 2
end
end
Upvotes: 7
Reputation: 1623
Start using concerns, RubyOnRails has this beautiful pattern to refactor code.
Check out this:
Upvotes: 1