Sahil Rally
Sahil Rally

Reputation: 541

Best way to define Constants in Ruby/ RoR at one place

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

Answers (3)

bixente.bvd
bixente.bvd

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

Sergio Tulentsev
Sergio Tulentsev

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

Sandip Mane
Sandip Mane

Reputation: 1623

Start using concerns, RubyOnRails has this beautiful pattern to refactor code.

Check out this:

http://vaidehijoshi.github.io/blog/2015/10/13/stop-worrying-and-start-being-concerned-activesupport-concerns/

Upvotes: 1

Related Questions