Class: InPlaceRelation::Wrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/in_place_relation.rb

Constant Summary collapse

METHODS_TO_WRAP =

ASSOCIATION_METHODS was removed in Rails 4, its contents put into the other constants

(ActiveRecord::Relation.const_defined?( :ASSOCIATION_METHODS ) ? ActiveRecord::Relation::ASSOCIATION_METHODS : []) + ActiveRecord::Relation::MULTI_VALUE_METHODS + ActiveRecord::Relation::SINGLE_VALUE_METHODS + [:merge]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(relation) ⇒ Wrapper

Returns a new instance of Wrapper.



38
39
40
# File 'lib/in_place_relation.rb', line 38

def initialize( relation )
  @relation = relation
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/in_place_relation.rb', line 46

def method_missing( meth, *args, &block )
  result = @relation.send( meth, *args, &block )
  # Wrap dynamically into a method if the result is a Relation - this makes
  # it work with scopes
  if result.is_a?( ActiveRecord::Relation )
    singleton_class.class_eval do
      define_method( meth ) do |*args, &block|
        @relation = @relation.send( meth, *args )
        return self
      end
    end
    @relation = result
    return self
  else
    return result
  end
end

Instance Attribute Details

#relationObject (readonly)

Wrapped ActiveRecord::Relation object



24
25
26
# File 'lib/in_place_relation.rb', line 24

def relation
  @relation
end

Instance Method Details

#in_placeObject



64
65
66
# File 'lib/in_place_relation.rb', line 64

def in_place
  return self
end

#inspectObject



42
43
44
# File 'lib/in_place_relation.rb', line 42

def inspect
  return "#{self.class}:#{object_id}"
end

#to_procObject

This is as stupid as possible, but ActiveRecord::Relation.merge expects:

  • a Hash

  • a Relation

  • something responding to to_proc and doing merge within

So I guess duck typing is now a no-go since 4.2…



73
74
75
76
# File 'lib/in_place_relation.rb', line 73

def to_proc
  rel = relation
  return -> { ActiveRecord::Relation::Merger.new(self, rel).merge }
end