ruby-on-railsrubyruby-on-rails-4booleanvirtus

Use boolean attribute helper methods when extending from Virtus.model on the fly


Let's say I have a Virtus model User with a boolean attribute active:

class User
  include Virtus.model 
  attribute :active, Boolean, default: false, lazy: true
end

Then I could user a helper method active?:

User.new.active? # => false
User.new(active: true).active? # => true

But when I try to extend from Virtus.model and define a boolean attribute on the fly:

class User; end
user = User.new
user.extend(Virtus.model)
user.attribute(:active, Axiom::Types::Boolean, default: false, lazy: true)
user.active = true

and use a helper method active? I get a NoMethodError kinda exception.

user.active? # => NoMethodError: undefined method `active?' for

Is there any possibility of using helper methods in this situation?


Solution

  • Most probably there is another gem in your project that defines a top-level Boolean class and it clashes with the Boolean attribute methods. Mongoid, for example, is known to do that. In such case, the Virtus README suggests using the Axiom::Types::Boolean type of the attribute instead.

    However, when I tried this, it didn't help. I believe the README is actually wrong, the correct type being noted in the Issue #234 comment: Virtus::Attribute::Boolean.

    A complete working example:

    class User; end
    user = User.new
    user.extend(Virtus.model)
    user.attribute(:active, 
                   Virtus::Attribute::Boolean,   # <- note the type
                   default: false, lazy: true)
    user.active = true
    user.active?
    #=> true