Giant Japanese Robot

Better living through pop culture.
Sep 18
Permalink

Ruby on Rails: String to Boolean

Really, this should be simpler. Knowing Rails folks there is probably some deep philosophical reason this isn’t included, but I hold no grudge.

So….I’m converting objects back and forth to JSON and when they return all my pretty Booleans are converted into strings. My assumption was that there was a handy little .to_b(ool) method for String, but alas there does not appear to be. This is the method I ended up writing.

  1.      def object_to_boolean(value)
  2.         return [true, “true”, 1, “1”, “T”, “t”].include?(value.class == String ? value.downcase : value)
  3.      end

As always I am open to suggestions and improvements.

Comments (View)

blog comments powered by Disqus