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

1

7

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?

Opponent answered 15/5, 2017 at 10:25 Comment(4)
is user.active is also giving error? I mean without ?Emulsoid
@Md.FarhanMemon, no user.active works just fine. It is just that using active? looks a lot more distinct in that way and doesn't differ from other boolean logic checks in the application.Opponent
I see, what's the full error btw? undefined method active?' for.....?`Emulsoid
@Md.FarhanMemon the name of the instance object (NoMethodError: undefined method `active?' for #<User:0x007fb18fc59cc8>)Opponent
C
5

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 
Childs answered 15/5, 2017 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.