ruby-on-railsregexrubyenvironment-variablesruby-on-rails-5

Can we put regex string in enviroment variable?


I have code in rails to check CORS from list of domain in env like this

config.middleware.insert_before 0, Rack::Cors do
  domains = ""

  if ENV["DOMAIN_CORS"].present? && !ENV["DOMAIN_CORS"].empty?
    domains = ENV["DOMAIN_CORS"].split(",").map { |origin| origin.strip }
  end

  allow do
    origins domains
    resource "*", headers: :any, methods: [:get, :post, :put, :delete, :options], credentials: true
  end
end

And i have env like this DOMAIN_CORS = "https://example1.com, https://example2.com"

Above code work fine to check cors for those two domains, but if I want to allow all subdomain of example.com to work, after read somepost from here

https://github.com/cyu/rack-cors/issues/30

I need to have regex check like

(.*?)\.example\.com

I set env to

DOMAIN_CORS = "https://example1.com, https://example2.com, (.*?)\.example\.com, /(.*?)\.example\.com/" 

But all ways seem not work, so is there anyway that I can put regex string in env for this case ? . Tks


Solution

  • enter image description here

    As you can see what they use in the linked rack-cors issue is of a Regexp class, and not a String as in your case.

    I suggest concatenating 2 environment variables:

    and map them accordingly:

    ENV['STRING_DOMAIN_CORS'].split(",").map { |origin| origin.strip } +
    ENV['REGEXP_DOMAIN_CORS'].split(",").map { |origin| origin.strip }.map { |origin| Regexp.new(origin) }
    

    enter image description here