-
-
Save ChuckJHardySnippets/2000623 to your computer and use it in GitHub Desktop.
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 |
blank? throws a NoMethodError in Ruby 2.2.1, I think because blank? is now replaced with empty?
@pacharanero, #blank? is Ruby on Rails method only.
@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.)
so after defining my module, I just include it. And I don't want that to effect system wide.
Examples: