Category: Rails

Rails routes: limiting access to application parts from certain domains (hosts)

Sometimes we want to handle different parts of a single application from different domains. A good example of such an approach is when we have a scope containing our API. Wouldn't it be great if it could be served from a different domain than the rest of the application? Of course yes! Approach like this (separating the API from the rest of the app) is used in several popular web applications. For example in Twitter. The app is under twitter.com and the API lies under the api.twitter.com url. When you have a smaller Rails app, probably you maintain the API-part and the user-part in one Rails project. The separate domains approach allows you to easily move to the two different apps, when the time comes.

So, how to limit access to the app parts based on the domain? Let's use constraints. Let's assume, that we have a scope called :api and the scope called :ui. Each scope represents a module in our app:

scope :module => :api do
  # Some resources and additional routes here
  # Api::SomeController...
end

scope :module => :ui do
  # Some resources and additional routes here
  # Ui::SomeController...
end

To make it domain-accessible we just need to wrap it with a block like this one:

constraints(:host => 'my_domain') do
# Routes here
end

where the my_domain is a domain that should be used with our app part. So for the example above, it would look like this:

constraints(:host => 'api.example.com') do
  scope :module => :api do
    # Some resources and additional routes here
    # Api::SomeController...
  end
end

constraints(:host => 'my.app.example.com') do
  scope :module => :ui do
    # Some resources and additional routes here
    # Ui::SomeController...
  end
end

Mocking Doorkeeper access token with Mocha

Recently I've been testing some stuff behind Doorkeeper and I needed to mock Doorkeeper token to return a stub. In older Doorkeeper versions it was done like this:

stub_prs = {
  :accessible? => true,
  :resource_owner_id => (user.nil? ? @user.id : user.id),
  :expired? => false
}
Doorkeeper::AccessToken.expects(:find_by_token).returns(stub(stub_prs))

However in a new Doorkeeper version, the've changed something and my mockings stopped working. So if you use newest Doorkeeper version, the mock should look like this:

stub_prs = {
  :accessible? => true,
  :resource_owner_id => (user.nil? ? @user.id : user.id),
  :expired? => false
}.merge(params)
@controller.expects(:doorkeeper_token).returns(stub(stub_prs)).at_least_once

Copyright © 2025 Closer to Code

Theme by Anders NorenUp ↑