module Hobo::Model::FindFor

FIXME: should be FindByBelongsTo maybe

Public Instance Methods

method_missing_with_find_for(name, *args, &block) click to toggle source
# File lib/hobo/model/find_for.rb, line 10
def method_missing_with_find_for(name, *args, &block)
  if name.to_s =~ /(.*)_by_(.*)/
    # name matches the general form

    collection_name = $1.to_sym
    anchor_association_name = $2.to_sym
    if (refl = self.class.reflections[collection_name.to_s]) && refl.macro == :has_many
      # the association name matches (e.g. comment_for_...)

      if (anchor_refl = refl.klass.reflections[anchor_association_name.to_s]) && anchor_refl.macro == :belongs_to
        # the whole thing matches (e.g. comment_for_user)


        #self.class.class_eval %{
        #  def #{name}(anchor)
        #    result = if #{collection_name}.loaded?
        #               #{collection_name}.detect { |x| x.#{anchor_association_name}_is?(anchor) }
        #             else
        #               #{collection_name}.#{anchor_association_name}_is(anchor).first
        #             end
        #    result ||= #{collection_name}.new(:#{anchor_association_name} => anchor)
        #    result.origin = self
        #    result.origin_attribute = "#{name}.'#{anchor_id_expr}'"
        #    result
        #  end
        #}

        self.class.class_eval %Q{
          def #{name}
            Hobo::Model::FindFor::Finder.new(self, '#{name}', :#{collection_name}, :#{anchor_association_name})
          end
        }

        return send(name, *args)
      end
    end
  end

  method_missing_without_find_for(name, *args, &block)
end

Public Class Methods

included(base) click to toggle source
# File lib/hobo/model/find_for.rb, line 6
def self.included(base)
  base.alias_method_chain :method_missing, :find_for
end