Skip to content

Instantly share code, notes, and snippets.

@gbarrancos
Created January 3, 2011 20:33
Show Gist options
  • Save gbarrancos/763916 to your computer and use it in GitHub Desktop.
Save gbarrancos/763916 to your computer and use it in GitHub Desktop.
Mongoid doesn't provide typed Array declarations, so you have to to convert them by hand when pushing params from request to your model instance. This one helps by defining the conversion callback automatically
# class YoClass
# include Mongoid::Document
# include FieldConverters
#
# field :an_array, type => Array
# convert_array [:an_array], :to_array_of => Integer, :before => :validate
# end
module FieldConverters
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
@@CONVERTERS = { Integer => :to_i, String => :to_s, Float => :to_f}.freeze
def convert_array(attributes, opts)
class_eval do
set_callback(opts[:before], :before) do |model|
attributes.each do |attribute|
val = self.send(attribute)
self.send((attribute.to_s + '='), []) if val.nil?
val.map!(&@@CONVERTERS[opts[:to_array_of]])
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment