Using Rails Routing Helpers in Ruby Object (PORO)

Using Rails Routing Helpers in Ruby Object (PORO)

Rails routing helpers can be imported into any class that you define in your project. The easiest way is to use include Rails.application.routes.url_helpers

Here’s an example of PORO that implements logic for showing a sign_in link or register link depending on if the user exists or not.

class EmailLinks
  include Rails.application.routes.url_helpers

  attr_reader :email

  def initialize(email)
    @email = email
  end

  def sign_in_link
    user_exists? ? root_url : register_url(email: email)
  end

  def sign_in_link_text
    user_exists? ? "Sign In" : "Register for your account"
  end

  def user_exists?
    User.exists?(email: email)
  end

end

However, the _url methods need a definition of your host which is set in default_url_options. This value can be set in our initialize method. We can inject a Mailer class as paramater and we use the setting defined in our <a target="_blank" rel=“nofollow” “http://rubyonrails.org/">Ruby on Rails project setttings.

Our modified class will look like this:

class EmailLinks
  include Rails.application.routes.url_helpers

  attr_reader :email

  def initialize(email, mailer = UserMailer)
    self.default_url_options = mailer.default_url_options
    @email = email
  end

  def sign_in_link
    user_exists? ? root_url : register_url(email: email)
  end

  def sign_in_link_text
    user_exists? ? "Sign In" : "Register for your account"
  end

  def user_exists?
    User.exists?(email: email)
  end

end