Custom attribute serialization

mrbrdo edited this page Jun 13, 2012 · 2 revisions

By default, has_moderated serializes all your model attributes using #to_yaml. So if all your attributes support YAML serialization, you usually don't need to do anything.

If you want, however, you can serialize attributes yourself. To do this you just need to provide an instance method in your model called get_moderation_attributes, which should return a Hash with all the attributes and their values.

class Post < ActiveRecord::Base
  def get_moderation_attributes
    { :attr1 => "ok" }
  end
end

You can even use alias_method_chain to only override or add specific attributes:

class Post < ActiveRecord::Base
  alias_method_chain :get_moderation_attributes, :my
  def get_moderation_attributes_with_my
    get_moderation_attributes_without_my.merge(:extra => "ok")
  end
end

This can be useful to set virtual attributes - this approach is used in lib/has_moderated/carrier_wave.rb.