[Proposal] define String#json? to return boolean value if the object is json string

56 views
Skip to first unread message

Akira

unread,
Apr 19, 2018, 5:59:49 AM4/19/18
to Ruby on Rails: Core
I was looking for a method that return boolean value if the object is json string.
I think there is no support for this idea on activesupport/lib/active_support/core_ext/string .

Here is my proposal to include this feature.

activesupport/lib/active_support/core_ext/string/json.rb

class String
  # An object is json string if it’s parseable by JSON.parse.
  # return true if it's parseable.
  # return false if it is not parseable.
  def json?
    !!JSON.parse(self)
  rescue
    false
  end
end

T.J. Schuck

unread,
Apr 19, 2018, 11:37:21 AM4/19/18
to rubyonra...@googlegroups.com
Note that I'm not on the core team, so my answer is far from final, but: just a heads up that the current refrain on changes to Active Support (and particularly the core extensions) is roughly "We avoid adding new things to Active Support unless they are used in the framework or by a large number of applications, so we need to know why you think this feature is useful to take any decision" — example.

You could open a PR with your change to get more discussion since it's a reasonably minimal and understandable diff, but expect pushback unless you have a particularly compelling use case. Since this is a core extension update to String, you could also lobby to have it included in Ruby directly instead.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-core+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Xavier Noria

unread,
Apr 19, 2018, 12:57:56 PM4/19/18
to rubyonrails-core
Definitely don't see this in the String class.

If you like that API you can throw that code in the initializers of your app, though.
Reply all
Reply to author
Forward
0 new messages