Monday, June 11, 2012

Check if string is a JSON in Rails


# config/initializers/string_methods.rb

require 'json'

class String
  def is_json?
    begin
      !!JSON.parse(self)
    rescue
      false
    end
  end
end

1 comment:

Anonymous said...

Two improvements here:
- core_ext is a better place than initializers/
- monkey patching isn't that best, refinements or model level (using concerns) is much better