Last active
August 29, 2015 14:27
-
-
Save erchn/46d7fd58adb59863784a to your computer and use it in GitHub Desktop.
Redefinition of Rails.env to support a hierarchy of environments, tested on 3.2.17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Override Rails.env so we can have a env method that support this environment plus or minus other environments as true | |
# This initializer file is named 01_rails so it executes before any others | |
module Rails | |
# Mini-helper class which subclasses String, duplicating the base of ActiveSupport::StringInquirer | |
# Adds support for comparing hierarchy of environments, the method_name vs. current Rails.env | |
# | |
# Rails.env # => "development" | |
# Rails.env.development? # => true | |
# Rails.env.production? # => false | |
# Rails.env.production?(:<) # => true (dev, test, qa, stage) | |
# Rails.env = "stage" # => "stage" | |
# Rails.env.stage?(:<) # => false (dev, test, qa) | |
# Rails.env.stage?(:>=) # => true (stage && production) | |
class MyStringInquirer < String | |
private | |
def respond_to_missing?(method_name) | |
method_name[-1] == '?' | |
end | |
def method_missing(method_name, arg=nil) | |
envs = ["development", "test", "qa", "stage", "production"] | |
comparators = [:>, :>=, :<, :<=, :==] | |
if method_name[-1] == '?' | |
name = method_name[0..-2] | |
self_pos = envs.index(self) | |
name_pos = envs.index(name) | |
if arg.nil? || name_pos.nil? || self_pos.nil? | |
self == name | |
elsif comparators.include?(arg) | |
self_pos.public_send(arg, name_pos) | |
end | |
else | |
super | |
end | |
end | |
end | |
class << self | |
def env | |
@_env = nil if @_env.class.name == 'ActiveSupport::StringInquirer' | |
@_env ||= MyStringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development") | |
end | |
def env=(environment) | |
@_env = MyStringInquirer.new(environment) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment