Created
January 3, 2011 20:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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