2

I'm using Virtus gem and trying to autocast Strings to Booleans, but without success... If you can see what's wrong with this code...

Virtus.coercer do |config|
  config.string.boolean_map = { 'true' => true, 'false' => false }
end

class BookingWizard
  include Virtus

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attribute :know_doctor, Boolean, default: false
end

1.9.3 (main):0 > b = BookingWizard.new
=> #<BookingWizard:0x007fea748bf338
 @know_doctor=false>
1.9.3 (main):0 > b.know_doctor = "true"
=> "true"
1.9.3 (main):0 > b.know_doctor
=> "true"
1.9.3 (main):0 > b.know_doctor.class
=> String
1.9.3 (main):0 > Virtus.coercer[String].to_boolean("true")
=> true
Kris
  • 19,188
  • 9
  • 91
  • 111
Nicolas Blanco
  • 11,164
  • 7
  • 38
  • 49
  • 1
    The boolean_map is transposed. I think you want `{'true' => true, 'false' => false}` – Shawn Balestracci May 15 '13 at 09:41
  • I didn't get your problem. – Arup Rakshit May 15 '13 at 09:41
  • Thanks @ShawnBalestracci I've updated the code with the inverted map, it still does not work :( – Nicolas Blanco May 15 '13 at 09:59
  • OK that was because of a mongoid bug : https://github.com/mongoid/mongoid/issues/2648 – Nicolas Blanco May 15 '13 at 10:27
  • @NicolasBlanco did you get autocasting from Strings to Booleans to work? I followed the virtus documentation at https://github.com/solnic/virtus#building-modules-with-custom-configuration , but came across the same issue you had. – EricC May 22 '15 at 14:33
  • @NicolasBlanco the github issue you linked does not exist anymore. Are you having the same issue still? – onebree Aug 04 '15 at 14:09
  • 1
    @EricC I suggest that is you are having the same issue, first post an issue on Github. If no luck, then ask a question yourself, simply linking to this one for reference. :-) – onebree Aug 04 '15 at 14:10
  • The comments seem to indicate that this problem is solved, so I'll vote to close as "not reproducible". @NicolasBlanco, if I am in error, let me know and we'll re-open it. – Wayne Conrad Aug 04 '15 at 18:13

1 Answers1

0

Try using Axiom::Types::Boolean instead of Boolean in case you already have a Boolean class defined.

class BookingWizard
  include Virtus

  attribute :know_doctor, Axiom::Types::Boolean, default: false
end

If this works you probably have a ::Boolean class which is being found before the Virtus one. Use show-source Boolean in pry to find your Boolean class.

Kris
  • 19,188
  • 9
  • 91
  • 111