0

I would like to know how I could use ActiveRecord in the routes.rb file on my Rails application.

I am creating some optional modules which can be enabled or disabled dynamically. I don't want the routes to exists if the module is disabled so I created a condition around the optional routes. In development it's work properly but in the test environment, my query returns nil even if my fixtures are properly settled.

How can I make tests to use my fixtures when I am using OptionalModule.all ?

Thanks !

Here is my routes.rb file:

Rails.application.routes.draw do
  optional_modules = OptionalModule.all # this returns nil in test mode

  # by_name is a scope defined in the model
  if optional_modules.by_name('GuestBook').enabled?
    get 'toggle_guest_book_validated/:id', to: 'admin/guest_books#toggle_guest_book_validated', as: :toggle_guest_book_validated
  end
end

My fixtures:

guest_book:
  name: GuestBook
  enabled: true

My project:

  • Rails 4.2
  • Ruby 2.2.0
anthony
  • 640
  • 1
  • 10
  • 32

1 Answers1

1

If I wanted to enable or disable routes dynamically, I'd try to set the flags using environment variables instead of storing the flags in the database state (which, if it's a relational database, isn't the most efficient place to store global flags anyway). Then in routes.rb you could just check for the presence / truthiness of each environment variable:

if ENV['MODULE_GUEST_BOOK']
  # enable fancy routes
end
Topher Hunt
  • 4,404
  • 2
  • 27
  • 51