Search code examples
ruby-on-railsrubyclassproduction-environment

How to define a Rails environment-specific class?


I've got a class in Rails that is using factory girl which will not be defined in a production environment, so I need to only load the class if the environment is not production. I've tried using a simple return statement as seen below, but it returns an Invalid return (SyntaxError):

return if Rails.env.production?


Additional Information

I'm using the mail_view gem. Here's the full error trace (only 1 line was printed):

mail_preview.rb: app/mailers/mail_preview.rb:1: Invalid return (SyntaxError)

Here's the relevant part of the file:

return if Rails.env.production?

class MailPreview < MailView
  include FactoryGirl::Syntax::Methods

  # ...
end

Solution

  • I think you can do:

    unless Rails.env.production?
      class MailPreview < MailView
        include FactoryGirl::Syntax::Methods
        # ...
      end
    end
    

    Though then in your code you need to check if the constant exists. I'd rather leave it open, and do a check in your controller or model or wherever if it's production, use this class.