Module: Netzke::ActiveRecord::Basepack
- Defined in:
- lib/netzke/active_record/basepack.rb
Overview
Provides extensions to all ActiveRecord-based classes
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#method_missing(method, *args, &block) ⇒ Object
Allow nested association access (assocs separated by “.” or “__”), e.g.: proxy_service.asset__gui_folder__name Example:.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
Allow nested association access (assocs separated by “.” or “__”), e.g.: proxy_service.asset__gui_folder__name Example:
Book.first.genre__name = 'Fantasy'
is the same as:
Book.first.genre = Genre.find_by_name('Fantasy')
The result - easier forms and grids that handle nested models: simply specify column/field name as “genre__name”.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/netzke/active_record/basepack.rb', line 18 def method_missing(method, *args, &block) # if refering to a column, just pass it to the original method_missing return super if self.class.column_names.include?(method.to_s) split = method.to_s.split(/\.|__/) if split.size > 1 if split.last =~ /=$/ if split.size == 2 # search for association and assign it to self assoc = self.class.reflect_on_association(split.first.to_sym) assoc_method = split.last.chop if assoc begin assoc_instance = assoc.klass.send("find_by_#{assoc_method}", *args) rescue NoMethodError assoc_instance = nil logger.debug "!!! no find_by_#{assoc_method} method for class #{assoc.klass.name}\n" end if (assoc_instance) self.send("#{split.first}=", assoc_instance) else logger.debug "!!! Couldn't find association #{split.first} by #{assoc_method} '#{args.first}'" end else super end else super end else res = self split.each do |m| if res.respond_to?(m) res = res.send(m) unless res.nil? else res.nil? ? nil : super end end res end else super end end |
Class Method Details
.included(base) ⇒ Object
4 5 6 |
# File 'lib/netzke/active_record/basepack.rb', line 4 def self.included(base) base.extend ClassMethods end |