There are various ways to access the host and port in a Rails application. Here are three common approaches:

  1. Passing host and port from the controller to the model
  2. Using environment variables
  3. Using config.action_mailer.default_url_options

1. Pass from Controller to Model:

In this approach, the host and port are retrieved from the request object in the controller and passed to the model.

Controller:

def show
     host = request.host
     port = request.port
  @some_model = MyModel.new_with_url(host, port)
end

Model:

class MyModel < ApplicationRecord
      def self.new_with_url(host, port)
      	base_url = "http://#{host}:#{port}/"
     	# Use base_url in model logic
   end
end

2. Use Environment Variables:

Host and port can be stored as environment variables and accessed directly in the model or any other application part.

host = ENV[‘HOST’]
Port = ENV[‘PORT’]

This keeps the code decoupled from the request lifecycle and ensures flexibility across different environments.

3. Use config.action_mailer.default_url_options:

Host and port can also be configured in the respective environment files, such as

config/environments/production.rb:
config.action_mailer.default_url_options = { host: 'my.application.com', port: 80 }

These can then be accessed as follows:

host = Rails.application.config.action_mailer.default_url_options[:host]
port = Rails.application.config.action_mailer.default_url_options[:port]

This method is particularly useful for generating consistent URLs for system-generated links like emails.

Need Help With Ruby On Rails Development?

Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.

Hire Ruby on Rails Developer

Support On Demand!

Related Q&A