Ruby has Integer(...) and Float(...), but does it have Boolean(…) for things like:
Boolean(ENV[“SOME_FLAG”])
What's the Ruby idiom here?
Ruby has Integer(...) and Float(...), but does it have Boolean(…) for things like:
Boolean(ENV[“SOME_FLAG”])
What's the Ruby idiom here?
001> ENV["FLAG"]
=> "false"
002> !!ENV["FLAG"]
=> true
@llimllib @getajobmike but it's not what you want to achieve :)
I use Dry::Types for this.
Dry.Types::Params::Bool[ENV["FLAG"]]
@floehopper @getajobmike yeah, if ruby provided it, I assume it'd look something like this.
https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
@getajobmike Nancy Sinatra it:
Bang bang (my baby shot me down)
irb(main):003> ENV["FOO"] = "0"
=> "0"
irb(main):004> !!ENV["FOO"]
=> true
Would you expect this behavior?
@getajobmike the most intuitive env var APIs for Ruby users are the ones that only check for presence rather than contents (imho) but I know some do what you’re describing
Unfortunately if you want to provide a default value for the env var (say, on Heroku) then there is no way to force unset a default config.
This gem check if required env variables are present and its format using the .env and .env.sample files from Dotenv. - fastruby/dotenv_validator
@getajobmike Just today I noticed this is how it works. In a Rails controller `request.xhr? # => 0` when true.
I think JS is, infamously, the only language where you'd expect `!!"0" == true`.
@getajobmike The boolean gem seems to provide the ‘Boolean()’ method that you want:
@getajobmike I have always used ENV["SOME_FLAG”] == "true”
I am definitely Team I Don’t Like 78 Forms of Boolean Representation, so anything other than the string "true" is considered false to me.
But I would love to see a Boolean data type and coercion method to address this issue from stdlib
["1", "y", "yes", "true"].include?(ENV["FLAG"].to_s.downcase ) 🙃
And of course for the opposite:
["0", "n", "no", "false"].include?(ENV["FLAG"].to_s.downcase)
@caleb @getajobmike lol, apologies.
I should have guessed :)
@jc00ke @getajobmike Since ENV isn't a hash, it could theoretically specialize on string formats like this, letting it return numbers or booleans.
FLAG=true SIDEKIQ_WORKERS=5
ENV.boolean("FLAG") # => true
ENV.boolean("UNSET_FLAG") # => nil
ENV.integer("SIDEKIQ_WORKERS") # => 5
https://gist.github.com/jgaskins/de1f724e980ce29e31ac90eb2b5bab1f