Class: Hobo::Model::FindFor::Finder

Inherits:
Object
  • Object
show all
Defined in:
lib/hobo/model/find_for.rb

Instance Method Summary collapse

Constructor Details

#initialize(owner, name, collection, anchor_association) ⇒ Finder

Returns a new instance of Finder.



53
54
55
56
57
# File 'lib/hobo/model/find_for.rb', line 53

def initialize(owner, name, collection, anchor_association)
  @association = owner.send(collection)
  @anchor_reflection = @association.member_class.reflections[anchor_association.to_s]
  @name = name
end

Instance Method Details

#[](anchor_or_id) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/hobo/model/find_for.rb', line 67

def [](anchor_or_id)
  anchor = if anchor_or_id.is_a?(String)
             id, klass = anchor_or_id.split(':')
             (klass.constantize || @anchor_reflection.klass).find(id)
           else
             anchor_or_id
           end
  result = if @association.loaded?
             @association.detect { |x| x.send("#{@anchor_reflection.name}_is?", anchor) }
          else
             @association.send("#{@anchor_reflection.name}_is", anchor).first
          end
  result ||= @association.new(@anchor_reflection.name => anchor)


  result.origin = self
  result.origin_attribute = if @anchor_reflection.options[:polymorphic]
                              "#{anchor.id}:#{anchor.class.name}"
                            else
                              "#{anchor.id}"
                            end
  result
end

#originObject



59
60
61
# File 'lib/hobo/model/find_for.rb', line 59

def origin
  @association.proxy_owner
end

#origin_attributeObject



63
64
65
# File 'lib/hobo/model/find_for.rb', line 63

def origin_attribute
  @name
end