Created
January 20, 2012 21:02
-
-
Save sriranggd/1649542 to your computer and use it in GitHub Desktop.
Patch to fix Mongoid aliased names shortcomings
This file contains hidden or 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
| # Copy the contents to a file named mongoid_aliased_field.rb and drop it in the lib/ directory of your Rails app | |
| # Add lib/ to autoload paths in the config/application.rb | |
| # require 'mongoid_aliased_field' right after you add the lib/ to autoload path | |
| # | |
| # #Autoload the files in the lib directory | |
| # config.autoload_paths += %W(#{config.root}/lib) | |
| # | |
| # # Require the mongoid_aliased_field monkey patching file explicitly | |
| # require 'mongoid_aliased_field' | |
| module Mongoid | |
| module Fields | |
| module ClassMethods | |
| # | |
| # This is a wrapper for the Mongoid's +field+ method, supplementing it | |
| # with the following additions : | |
| # * Defines getter and setter methods for the short original field name | |
| # * Defines dirty attribute tracking methods for the long aliased field name | |
| # | |
| # The additional methods defined are just thin wrappers around the already available | |
| # ones. They do not do anything with the data. | |
| # | |
| # The options are passed as it is to the +field+ method | |
| # Using this is exactly same as the +field+ method | |
| # | |
| def aliased_field(field_name, options = {}) | |
| alias_name = options[:as] | |
| field(field_name, options) | |
| if alias_name | |
| define_method("#{field_name}") { __send__(alias_name) } | |
| define_method("#{field_name}=") { |value| __send__("#{alias_name}=", value) } | |
| attribute_methods_suffixes = ['_change', '_changed?', '_was', '_will_change!'] | |
| attribute_methods_suffixes.each do |suffix| | |
| define_method("#{alias_name}#{suffix}") { __send__("#{field_name}#{suffix}") } | |
| end | |
| end | |
| end | |
| end #__End of module ClassMethods__ | |
| end #__End of module Fields__ | |
| end #__End of module Mongoid__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment