solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 228 forks source link

Alternative to old writer_class #211

Closed terlar closed 10 years ago

terlar commented 10 years ago

In the old API there was something called writer_class, it seems it is removed in the latest RC. What is the new way to do things like this:

class CategoryWriter < Virtus::Attribute::Writer::Coercible
  def coerce(value)
    case value
    when Integer then Category.find(value)
    when Category then value
    end
  end
end

class Product
  include Virtus.model
  attribute :category, Category, writer_class: CategoryWriter
end

Product.new(category: 5)

I have looked at the coercible examples, but they didn't work for this kind of operation.

I get NoMethodError: Expected 5 to respond to #to_hash from .../virtus-1.0.0.rc2/lib/virtus/attribute_set.rb:196:in 'coerce'

solnic commented 10 years ago

You can do this now:

class Product
  include Virtus.model

  attribute :category, Category, coercer: proc { |value|
    case value
    when Integer then Category.find(value)
    when Category then value
    end
  }
end
terlar commented 10 years ago

Thanks for the quick response, it works.

solnic commented 10 years ago

@terlar awesome and sorry for the inconvenience; that API you used was an intermediate state between 2 refactorings that I did when working on 1.0.0 and truth is I should've not released the first beta.

Anyhow, glad it works for you. Please report any other issues you might encounter as I'm planning to push the final 1.0.0 version really soon.