This website uses cookies to better the user experience of its visitors. Where applicable, this website uses a cookie control system, allowing users to allow or disallow the use of cookies on their computer/device on their first visit to the website. This complies with recent legislative requirements for websites to obtain explicit consent from users before leaving behind or reading files such as cookies on a user’s computer/device. To learn more click Cookie Policy.

Privacy preference center

Cookies are small files saved to a user’s computer/device hard drive that track, save, and store information about the user’s interactions and website use. They allow a website, through its server, to provide users with a tailored experience within the site. Users are advised to take necessary steps within their web browser security settings to block all cookies from this website and its external serving vendors if they wish to deny the use and saving of cookies from this website to their computer’s/device’s hard drive. To learn more click Cookie Policy.

Manage consent preferences

These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Cookies list
Name _rg_session
Provider rubygarage.org
Retention period 2 days
Type First party
Category Necessary
Description The website session cookie is set by the server to maintain the user's session state across different pages of the website. This cookie is essential for functionalities such as login persistence, ensuring a seamless and consistent user experience. The session cookie does not store personal data and is typically deleted when the browser is closed, enhancing privacy and security.
Name m
Provider m.stripe.com
Retention period 1 year 1 month
Type Third party
Category Necessary
Description The m cookie is set by Stripe and is used to help assess the risk associated with attempted transactions on the website. This cookie plays a critical role in fraud detection by identifying and analyzing patterns of behavior to distinguish between legitimate users and potentially fraudulent activity. It enhances the security of online transactions, ensuring that only authorized payments are processed while minimizing the risk of fraud.
Name __cf_bm
Provider .pipedrive.com
Retention period 1 hour
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to support Cloudflare Bot Management. This cookie helps to identify and filter requests from bots, enhancing the security and performance of the website. By distinguishing between legitimate users and automated traffic, it ensures that the site remains protected from malicious bots and potential attacks. This functionality is crucial for maintaining the integrity and reliability of the site's operations.
Name _GRECAPTCHA
Provider .recaptcha.net
Retention period 6 months
Type Third party
Category Necessary
Description The _GRECAPTCHA cookie is set by Google reCAPTCHA to ensure that interactions with the website are from legitimate human users and not automated bots. This cookie helps protect forms, login pages, and other interactive elements from spam and abuse by analyzing user behavior. It is essential for the proper functioning of reCAPTCHA, providing a critical layer of security to maintain the integrity and reliability of the site's interactive features.
Name __cf_bm
Provider .calendly.com
Retention period 30 minutes
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to distinguish between humans and bots. This cookie is beneficial for the website as it helps in making valid reports on the use of the website. By identifying and managing automated traffic, it ensures that analytics and performance metrics accurately reflect human user interactions, thereby enhancing site security and performance.
Name __cfruid
Provider .calendly.com
Retention period During session
Type Third party
Category Necessary
Description The __cfruid cookie is associated with websites using Cloudflare services. This cookie is used to identify trusted web traffic and enhance security. It helps Cloudflare manage and filter legitimate traffic from potentially harmful requests, thereby protecting the website from malicious activities such as DDoS attacks and ensuring reliable performance for genuine users.
Name OptanonConsent
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonConsent cookie determines whether the visitor has accepted the cookie consent box, ensuring that the consent box will not be presented again upon re-entry to the site. This cookie helps maintain the user's consent preferences and compliance with privacy regulations by storing information about the categories of cookies the user has consented to and preventing unnecessary repetition of consent requests.
Name OptanonAlertBoxClosed
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonAlertBoxClosed cookie is set after visitors have seen a cookie information notice and, in some cases, only when they actively close the notice. It ensures that the cookie consent message is not shown again to the user, enhancing the user experience by preventing repetitive notifications. This cookie helps manage user preferences and ensures compliance with privacy regulations by recording when the notice has been acknowledged.
Name referrer_user_id
Provider .calendly.com
Retention period 14 days
Type Third party
Category Necessary
Description The referrer_user_id cookie is set by Calendly to support the booking functionality on the website. This cookie helps track the source of referrals to the booking page, enabling Calendly to attribute bookings accurately and enhance the user experience by streamlining the scheduling process. It assists in managing user sessions and preferences during the booking workflow, ensuring efficient and reliable operation.
Name _calendly_session
Provider .calendly.com
Retention period 21 days
Type Third party
Category Necessary
Description The _calendly_session cookie is set by Calendly, a meeting scheduling tool, to enable the meeting scheduler to function within the website. This cookie facilitates the scheduling process by maintaining session information, allowing visitors to book meetings and add events to their calendars seamlessly. It ensures that the scheduling workflow operates smoothly, providing a consistent and reliable user experience.
Name _gat_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _gat_UA-* cookie is a pattern type cookie set by Google Analytics, where the pattern element in the name contains the unique identity number of the Google Analytics account or website it relates to. This cookie is a variation of the _gat cookie and is used to throttle the request rate, limiting the amount of data collected by Google Analytics on high traffic websites. It helps manage the volume of data recorded, ensuring efficient performance and accurate analytics reporting.
Name _ga
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga cookie is set by Google Analytics to calculate visitor, session, and campaign data for the site's analytics reports. It helps track how users interact with the website, providing insights into site usage and performance.
Name _ga_*
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga_* cookie is set by Google Analytics to store and count page views on the website. This cookie helps track the number of visits and interactions with the website, providing valuable data for performance and user behavior analysis. It belongs to the analytics category and plays a crucial role in generating detailed usage reports for site optimization.
Name _gid
Provider rubygarage.org
Retention period 1 day
Type First party
Category Analytics
Description The _gid cookie is set by Google Analytics to store information about how visitors use a website and to create an analytics report on the website's performance. This cookie collects data on visitor behavior, including pages visited, duration of the visit, and interactions with the website, helping site owners understand and improve user experience. It is part of the analytics category and typically expires after 24 hours.
Name _dc_gtm_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _dc_gtm_UA-* cookie is set by Google Analytics to help load the Google Analytics script tag via Google Tag Manager. This cookie facilitates the efficient loading of analytics tools, ensuring that data on user behavior and website performance is accurately collected and reported. It is categorized under analytics and assists in the seamless integration and functioning of Google Analytics on the website.

How to Separate Features for Different Organizations in a Rails App

  • 28873 views
  • 11 min
  • Feb 01, 2018
Artem Z.

Artem Z.

Ruby/JS Developer

Sviatoslav A.

Sviatoslav A.

Copywriter

Share

When developing a multi-tenant Software as a Service application, designing the database layer is the first architectural problem you’ll have to address. But a database layer is only one part of the multi-tenant architecture.

When the same application instance is used by multiple organizations, otherwise called tenants, the app often provides identical core business functionalities to all of them. The main problem with the architecture layer that implements the business logic becomes evident when an organization wants more than just the core features.

As an emergency solution, your web development team can implement and deploy new features for all organizations. But will those other organizations ever need any of these new features? That’s questionable. Besides, if you decide to create subscription plans with extra features, then you’ll need to somehow restrict access to them.

So how can we approach development of a multi-tenant SaaS app when only a few organizations require additional functionality? We can’t just copy the app and extend it with new features individually for every new tenant, as doing so would break the multi-tenancy concept. Given that each application instance must be the same, we have to determine which features are available to which tenants.

We’ll review the two main techniques for separating feature stacks in a multi-tenant SaaS app. We’ll also name a library that your team can use to work on the business logic layer for a multi-tenant SaaS app. Although we’ll suggest solutions to separate feature stacks in a Rails-based SaaS application, the principles behind developing various feature stacks are similar no matter what backend framework you’re using.

Techniques for Working on Feature Stacks

Before we actually start developing a multi-tenant Rails-based SaaS app, we have to think about the following:

  • How to alter functionalities so that changes for one organization can’t influence functionalities available to other organizations
  • How to hide or show extra functionalities for organizations (this is especially important when implementing subscription plans)

When working on a multi-tenant SaaS app, we always have to address the first problem. As for the second problem, we may not need to focus on it. We only need to hide functionality if an application will provide additional features via subscription plans.

To develop multiple feature stacks, we can choose one of the following paths:

  • Build a fully custom implementation. This approach gives us supreme flexibility, especially with regard to updates. A custom implementation can take one of two forms:
    • A custom library that enables or disables features for organizations
    • Feature packages that separate feature stacks into separate modules; in Ruby on Rails development, such modules are called engines
  • Use an existing library. The Ruby ecosystem has plenty of libraries to restrict access to features for various user groups, but we’ll name the best and most popular libraries for feature separation.

The logic behind each of these three methods of dividing features is conditional statements. We must verify whether an organization has access to given functionality. Now let’s investigate each option for separating features in multi-tenant applications.

Custom Implementation of Feature Stacks

Implement Feature Toggles for Your App

A custom implementation of feature separation can be based on the feature toggles technique. Since each app is only one instance of a multi-tenant app, we can simply add or remove (toggle) features on the fly to show or hide certain features for different organizations. We can take advantage of the same feature toggles technique that’s often used in web development.

The feature toggles technique is chiefly used for A/B testing, for rolling out experimental features, and for testing new features on specific groups of customers. But feature toggles are also suitable for restricting access to features for organizations.

Overview diagram of feature toggles by Martin Fowler

With feature toggles, we can dynamically adapt app functionality for each organization. With each request from a new organization, the app will change the view to show only features that are available to that organization.

To set up permissions for multiple organizations, we have to make changes in several parts of the application:

  • Set up app configurations by enabling or disabling functionalities in controllers (in the case of Ruby on Rails).
  • Reflect changes in the view part of the app (the graphical user interface).

Roughly speaking, the controller part of the application is responsible for the actual logic behind checks of an organization’s rights. The view part (templates) is an endpoint that runs the check and renders only those parts that are available to an organization.

In this article, we'll offer three tutorials on feature separation in a Rails application. In these tutorials, we'll use the Blog feature as an example and we’ll show you how to give access to this feature only to specific parties. Each tenant (organization) should be able to manage their own articles but shouldn’t have access to other tenants’ articles.

Let's start with the first tutorial, which shows a custom implementation of feature separation:

  1. Generate Blog with scaffold in the console:
  2. Generate Tenant, Feature, and Subscription models in the console:
  3. Modify the Tenant model app/models/tenant.rb
  4. Modify the Feature model app/models/feature.rb
  5. Modify the Subscription model app/models/subscription.rb
  6. Create a new file app/models/feature_toggle.rb with the class FeatureToggle
  7. Modify app/controllers/application_controller.rb
  8. Add tenants, features and subscriptions with the console:
  9. Let's suppose that only HappinessCorp can show blog articles:

  10. Modify app/controllers/articles_controller.rb
  11. Modify the link to show article in app/views/articles/index.html.erb
  12. Run the following code in the console:
  13. Finally, open a browser and go to http://happinesscorp.lvh.me:3000/articles. Once you're logged into a happinesscorp account, you can see Blog links. If you change happinesscorp to feelgoodinc in the URL – http://feelgoodinc.lvh.me:3000/articles – the link becomes hidden. Even if the tenant inserts the link to an existing article, they’ll be redirected to http://feelgoodinc.lvh.me:3000/articles and see the message “You don’t have an access to this feature.”

    Error message when tenants change URLs

    As we can see, in order to reflect changes in the view we can simply use if statements: if a tenant is allowed to use a certain feature, then the additional layout is rendered on the screen.

    Using checks directly in templates works great when a complete feature must be made available for a given organization. But when the same feature is implemented differently for different organizations, then it’s better to move the logic to a lower-level implementation.

    When working on a Rails-based web application, we can basically create our own library that will help us determine an organization’s permissions.

    Next, let’s review another custom way to organize features using Rails engines.

    Encapsulate Feature Stacks in Engines

    Another way to separate features is by wrapping them in engines – small Ruby on Rails applications. The basic way this works is the same as in the previous example. When a user of a certain organization signs in and is authorized to use a feature, the application requests the proper engine.

    Here's a step-by-step tutorial on how to separate features by wrapping them into engines:

    1. Create a new mountable engine in your project folder with the console command:
    2. Also, create an engines folder to store the engine:
    3. Modify Gemfile
    4. Modify the real values of engines/feature_blog/feature_blog.gemspec to avoid warnings.
    5. Run
    6. Next, add a small initializer to the engines/feature_blog/lib/feature_blog/engine.rb file:
    7. Generate an articles scaffold for your engine:
    8. Next, modify config/routes.rb:
    9. Replace the files in /engines/feature_blog/app/views/feature_blog/articles/ with files from ./app/views/articles/ and then modify engines/feature_article/app/controllers/feature_article/articles_controller.rb
    10. At this point, nobody has access to your articles functionality. Grant access to the article feature to happinesscorp. To do that, run the following command in the console:

      Run the application. Now only happinesscorp has access to the article feature at this URL: http://happinesscorp.lvh.me:3000/articles.

      Using the Rails engines is beneficial as we can create typical, completely independent feature stacks. We recommend using engines as it’s a tad easier to configure engines than to use the previous approach.

      Using Rails engines to encapsulate features, however, also has downsides. One disadvantage is that you may end up having too many engines. Managing dozens of engines that implement different functionalities can create additional management overhead.

      But this approach is beneficial when you develop a white label application. A white label application looks like it’s fully customized for separate tenants, but it’s still essentially the same for all of them. Since a given organization might want to have a rather advanced feature stack, you might consider encapsulating that stack in an engine.

      So far, we’ve discussed two approaches for a custom implementation of the feature toggles technique: with and without Rails engines. But with Ruby on Rails-based applications, we can also benefit from using ready libraries when developing feature toggles. Using existing libraries makes it simpler to work on different features. We’ll discuss two libraries for Rails-based multitenant apps in the following section.

      Use a Ready Library to Separate Features for Organizations

      If you don’t want to spend time writing custom logic, you might opt for an existing library. The Ruby and Rails ecosystem counts more than a dozen libraries that are suitable for developing feature toggles.

  • Flipper is a beginner-friendly gem that makes it easy to switch features on and off. Flipper has many adapters including for Mongo, Redis, Sequel, Cassanity, and ActiveRecord.
  • Rollout is a relatively old yet still supported Ruby library that was designed to deliver functionalities to user groups such as admins, registered users, and new users. With Rollout, we can also manage features for organizations.
  • LaunchDarkly SDK for Ruby is an SDK for an advanced feature flag tool that allows you to easily create feature flags, create custom user roles and custom policies for those roles, gradually roll out features, perform A/B testing, and more. LaunchDarkly provides SDKs not only for Ruby but also for other programming languages including PHP, Python, and Go.
  • Feature Flipper is a small library that helps you restrict certain pieces of code to certain environments.
  • Setler implements the Feature Flag pattern and allows you to add settings to individual models.
  • Bandiera is a feature flagging solution that can be used with many programming languages and frameworks including Ruby and PHP since its communication is implemented with the help of a simple REST API.

We’ll use Flipper to develop feature toggles in our example.

Flipper was inspired by the Rollout gem, but Flipper proves a more flexible solution that Rollout. With Flipper, we’re not restricted to using Redis to store features. In addition to Redis, it’s possible to use other types of storage including but not limited to:

  • Relational databases with connectors
    • ActiveRecord, object-relational mapping designed for Ruby on Rails
    • Sequel, a toolkit that provides access to relational databases
  • MongoDB, a document-oriented database
  • Cassandra, a NoSQL database

Flipper introduced several concepts, namely the actor, feature, and gate. With a multi-tenant app, an actor is an organization that uses the app, and gates are responsible for checking if a feature can be used by an organization. The Flipper library also implements the adapter pattern, and you can easily extend the library with your own adapter to work with a specific relational database just like one of our RubyGarage developers did with Sequel.

Here’s our final tutorial that explains how to separate features with the Flipper gem.

  1. Modify the Gemfile:
  2. Then run
  3. Modify config/initializers/flipper.rb
  4. Modify config/routes.rb
  5. Modify app/models/tenant.rb
  6. Update engines/feature_blog/app/feature_blog/controllers/articles_controller.rb
  7. Then update engines/feature_blogapp/views/feature_blog/articles/index.html.erb
  8. Next, add helper_method :current_tenant in the ApplicationController.
  9. Update config/routes.rb
  10. Finally, run the server with

Register the Blog feature for the actor happinesscorp via the Flipper UI.

Aslo, register the feature_blog feature for the actor happinesscorp.

As a result, you’ll get the same behavior as in the previous example, only with a custom solution.

We’ve provided you with enough information to get started with Flipper. If you want to see a more detailed explanation of how Flipper works, you can check out a review written by the creator of the library.

So which approach – a custom approach or a ready library – should you choose for separating features in your own multi-tenant Rails-based application? There’s no definite answer, as the same approach won’t suit all Software as a Service applications. To get the most flexibility for your particular application, admittedly, it’s best to write fully custom logic to check each organization’s rights and show the appropriate features. But if time is expensive or in short supply, using Flipper is also a viable solution.

If you’re interested in getting even more useful articles on this topic, subscribe to our newsletter to receive a monthly update on our posts!

CONTENTS

Authors:

Artem Z.

Artem Z.

Ruby/JS Developer

Sviatoslav A.

Sviatoslav A.

Copywriter

Rate this article!

Nay
So-so
Not bad
Good
Wow
2 rating, average 5 out of 5

Share article with

Comments (2)
Armando Andini
Armando Andini almost 7 years ago
Very good article, shows a good example of Rails Engines. Thanks!
Reply
Maryna Z.
Maryna Z. almost 7 years ago
Armando, thanks a lot!
Reply

Subscribe via email and know it all first!