ruby-hyperloop / hyper-mesh

The project has moved to Hyperstack!! - Synchronization of active record models across multiple clients using Pusher, ActionCable, or Polling
https://hyperstack.org/
MIT License
22 stars 12 forks source link

add `#build / #new` and make `<< / #push` save like active record does #63

Open catmando opened 6 years ago

catmando commented 6 years ago

<< should save, and build should not.

change push's name to build (be careful push / << may be used internally in Hypermesh) and add a new push which does build(...).save and returns self.

only allow build on root collections (not scopes) as the scope behavior is to fill in the attributes to match the scope. (see https://github.com/ruby-hyperloop/hyper-mesh/issues/64)

have to add the old behavior back into the deprecation gem.

sfcgeorge commented 6 years ago

Patch for build - just extending current << behaviour to instantiate the model:

module ReactiveRecord
  class Collection
    unless method_defined?(:build)
      def build(**attrs)
        self << @association.klass.new(**attrs)
      end
    end
  end
end

Sketch of other methods, but I'm not sure the behaviour matches Rails, the docs aren't clear enough so some experimentation and looking at Rails code needed.

def <<(other)
  # push is current alias of <<
  push(other).save
end

def create(**attrs)
  build(**attrs)
  @owner.save
end

def create!(**attrs)
  build(**attrs)
  @owner.save!
end
catmando commented 6 years ago

push and << are aliases so it would have to be

def <<(other)
  build(other).tap { |r| r.save }
end