Class: InstantApi::Model::AssociationReflector
- Inherits:
-
Object
- Object
- InstantApi::Model::AssociationReflector
- Defined in:
- lib/instant_api/model/association_reflector.rb
Instance Method Summary collapse
- #association(klass, name) ⇒ Object
- #calculate_conditions(params) ⇒ Object
- #calculate_join ⇒ Object
- #foreign_key(assoc) ⇒ Object
-
#initialize(association_list) ⇒ AssociationReflector
constructor
A new instance of AssociationReflector.
- #join_table(assoc) ⇒ Object
- #to_class(symbol) ⇒ Object
Constructor Details
#initialize(association_list) ⇒ AssociationReflector
Returns a new instance of AssociationReflector.
25 26 27 |
# File 'lib/instant_api/model/association_reflector.rb', line 25 def initialize(association_list) @association_list = association_list end |
Instance Method Details
#association(klass, name) ⇒ Object
84 85 86 87 |
# File 'lib/instant_api/model/association_reflector.rb', line 84 def association(klass, name) klass.reflect_on_association(name.to_s.singularize.to_sym) || klass.reflect_on_association(name.to_s.pluralize.to_sym) end |
#calculate_conditions(params) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/instant_api/model/association_reflector.rb', line 52 def calculate_conditions(params) result = Hash.new result[:id] = params[:id] if params[:id] resource, *rest = *params.resources klass = to_class(resource) rest.map do |association_name| if (assoc = association(klass, association_name)) table = join_table(assoc) foreign_key = foreign_key(assoc) result[table] = { foreign_key => params[foreign_key] } end resource = association_name klass = to_class(resource) end result end |
#calculate_join ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/instant_api/model/association_reflector.rb', line 29 def calculate_join *associations, resource = *@association_list klass = to_class(resource) first, *rest = *associations.reverse result = [] if (assoc = association(klass, first)) result << assoc.name.to_sym klass = to_class(first) end if rest rest.each do |association_name| if (assoc = association(klass, association_name)) result << {klass.name.downcase.to_sym => assoc.name.to_sym} klass = to_class(association_name) end end end result end |
#foreign_key(assoc) ⇒ Object
80 81 82 |
# File 'lib/instant_api/model/association_reflector.rb', line 80 def foreign_key(assoc) assoc.foreign_key.to_sym end |
#join_table(assoc) ⇒ Object
72 73 74 75 76 77 78 |
# File 'lib/instant_api/model/association_reflector.rb', line 72 def join_table(assoc) if assoc.has_and_belongs_to_many? assoc.join_table.to_sym else assoc.name.to_sym end end |
#to_class(symbol) ⇒ Object
89 90 91 |
# File 'lib/instant_api/model/association_reflector.rb', line 89 def to_class(symbol) symbol.to_s.classify.constantize end |