There are various ways to access the host and port in a Rails application. Here are three common approaches:
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
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.
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.