Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom coercion for an EmbeddedValue? #88

Closed
namelessjon opened this issue May 9, 2012 · 2 comments
Closed

Custom coercion for an EmbeddedValue? #88

namelessjon opened this issue May 9, 2012 · 2 comments
Milestone

Comments

@namelessjon
Copy link

At the moment, if you have a Virtus object acting as an Embedded Value, you can't do any kind of custom coercion. Or even invoke the constructor, unless you pass in a hash. For example:

require 'virtus'

class Ability
  include Virtus

  attribute :rating, Integer, :default => 0
  attribute :favoured, Boolean, :default => false

  def initialize(rating_or_hash)
    if Integer === rating_or_hash
      self.rating = rating_or_hash
    else
      super
    end
  end
end

p Ability.new(1)
#=> #<Ability:0x1f01760 @rating=1>
p Ability.new(:rating => 1, :favoured => true)
#=> #<Ability:0x1f09380 @rating=1, @favoured=true>

class Character
  include Virtus

  attribute :driving, Ability
end

c = Character.new(:driving => 1)
p c
#=> #<Character:0x1c8c540 @driving=1>

c = Character.new(:driving => {:rating => 1})
p c
#=> #<Character:0x1c8b2b0 @driving=#<Ability:0x1c8b190 @rating=1>>

It would be helpful if in the Character.new(:driving => 1) case, the one could still be cast to an Ability. Perhaps via a custom coercion method? I'm not immediately sure how the best way to go about this would be.

@solnic
Copy link
Owner

solnic commented May 10, 2012

@namelessjon I would appreciate an integration spec showing the expected behavior

Also, are you saying it's not possible to override a virtus model constructor?

@namelessjon
Copy link
Author

@solnic I'll try and work one up. I do need to think about this a little more. It might be that what I actually want is a custom writer or coercer.

No, that does work in the general case. However, unless you pass a hash (or hash-ish?) to the EV, the constructor is never seen.

@solnic solnic closed this as completed in 8d8f58a May 11, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants