-
-
Save ChuckJHardySnippets/2000623 to your computer and use it in GitHub Desktop.
Ruby: Convert String to Boolean
This file contains hidden or 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
class String | |
def to_bool | |
return true if self == true || self =~ (/(true|t|yes|y|1)$/i) | |
return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i) | |
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"") | |
end | |
end |
@rubyrider: can't to_bool
be written more simply?
def to_bool
(!self.nil? && !(self.downcase.squish == 'false') && (self.downcase.squish == 'true' || self != '0' || self == '1'))
end
Also, I still don't understand how the approach doesn't effect things 'system wide'
Aren't you still monkeypatching String
?
You are using class_eval which is more flexible than
class Foo
#monkeypatch here
end
but it still looks like a system wide monkeypatch to me.
please correct me if I'm wrong, I'd like to know more.
http://stackoverflow.com/questions/9399358/monkey-patching-vs-class-eval
Am I missing something? What is extend ActiveSupport::Concern
doing here?
My approach to avoid affect whole system:
# This module add refinements to cast string to boolean
module StringToBooleanRefinements
refine String do
def to_bool
return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i)
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"")
end
end
end
Class that will uses this refinement
class RefinedStringClass
using StringToBooleanRefinements
def string_true
'true'.to_bool
end
def string_false
'false'.to_bool
end
end
(For reference, Ruby refinements was introduced in Ruby 2.0. So if you are stuck on some antique version, it will not work.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@pacharanero, #blank? is Ruby on Rails method only.