简体   繁体   中英

Get root_url in a Rails service

The app I'm working on makes heavy use of Rails services . My problem is I need to get the root url of the app, similar to how you would use root_url in a view, but this doesn't work in a service. Does anyone know a way to do this other than entering the url in each of my environment setting files?

Edit

I tried using Rails.application.routes.url_helpers.root_url as it suggests to do here stackoverflow.com/a/5456103/772309 but it expects you to pass the :host => ... in as a parameter. That's what Im trying to find.

Based on what I've read from the linked 'Rails services' article, the services are just plain old ruby objects. If that's the case, then you'd need to pass the root_url from the controller to the initializer of your service object. To extend the example from that article:

UsersController

class UsersController < ActionController::Base
  ...
  private
  ...

  def register_with_credit_card_service
    CreditCardService.new({
      card: params[:stripe_token],
      email: params[:user][:email],
      root_url: root_url
    }).create_customer
  end
end

CreditCardService

class CreditCardService
  def initialize(params)
    ...
    @root_url = params[:root_url]
  end
end

EDIT: Alternative solution that leverages the Rails.application.config

class UsersController < ActionController::Base
  before_filter :set_root_url

  def set_root_url
    Rails.application.config.root_url = root_url
  end
end

class CreditCardService
  def some_method
    callback_url = "#{Rails.application.config.root_url}/my_callback"
  end
end

Since you're opposed to putting it in your environment folders you could do something like below in your App controller

class ApplicationController < ActionController::Base
  def default_url_options
    if Rails.env.production?
      {:host => "myproduction.com"}
    else  
      {}
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM