Module: Subroutine::Association::ClassMethods
- Defined in:
- lib/subroutine/association.rb
Instance Method Summary collapse
-
#association(field, options = {}) ⇒ Object
Other options: - unscoped => set true if the record should be looked up via Type.unscoped.
- #field_with_associations(*args) ⇒ Object
Instance Method Details
#association(field, options = {}) ⇒ Object
Other options:
-
unscoped => set true if the record should be looked up via Type.unscoped
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/subroutine/association.rb', line 49 def association(field, = {}) if [:as] && [:foreign_key] raise ArgumentError.new(":as and :foreign_key options should be provided together to an association invocation") end class_name = [:class_name] poly = [:polymorphic] || !class_name.nil? as = [:as] || field unscoped = !![:unscoped] klass = class_name.to_s if class_name foreign_key_method = ([:foreign_key] || "#{field}_id").to_s foreign_type_method = foreign_key_method.gsub(/_id$/, "_type") if poly string foreign_type_method else class_eval <<-EV, __FILE__, __LINE__+1 def #{foreign_type_method} #{as.to_s.camelize.inspect} end EV end integer foreign_key_method field_without_associations as, .merge(association: true) class_eval <<-EV, __FILE__, __LINE__+1 def #{as}_with_association return @#{as} if defined?(@#{as}) @#{as} = begin #{as}_without_association || polymorphic_instance(#{klass.nil? ? foreign_type_method : klass.to_s}, #{foreign_key_method}, #{unscoped.inspect}) end end def #{as}_with_association=(r) @#{as} = r #{poly || klass ? "params['#{foreign_type_method}'] = r.nil? ? nil : #{klass.nil? ? "r.class.name" : klass.to_s.inspect}" : ""} params['#{foreign_key_method}'] = r.nil? ? nil : r.id r end EV alias_method :"#{as}_without_association", :"#{as}" alias_method :"#{as}", :"#{as}_with_association" alias_method :"#{as}_without_association=", :"#{as}=" alias_method :"#{as}=", :"#{as}_with_association=" end |
#field_with_associations(*args) ⇒ Object
16 17 18 19 20 21 22 23 24 25 |
# File 'lib/subroutine/association.rb', line 16 def field_with_associations(*args) opts = args. if opts[:association] args.each do |arg| association(arg, opts) end else field_without_associations(*args, opts) end end |