Sha256: 1bde770d06f77f2bef2e4cc1fd4e1eba3a8cbce2665c6f683a6248773e08bd37

Contents?: true

Size: 846 Bytes

Versions: 1

Compression:

Stored size: 846 Bytes

Contents

module Cave
  class ModelForm < Form
    def self.model klass=nil
      @@model ||= klass
    end

    def initialize instance=nil, attrs={}
      (instance, attrs = nil, instance) if instance.is_a? Hash
      super attrs
      self.for instance
    end

    def for instance
      @instance = instance
      check_instance_model
    end

    def persist!
      if @instance
        @instance.update_attributes attributes
      else
        @instance = self.class.model.create! attributes
      end
    end

    private #-----------

    def check_instance_model
      model = self.class.model
      if @instance
        raise TypeError.new("Instance #{@instance} is not a #{model}") unless @instance.is_a? model
      else
        raise TypeError.new("Please specify a model class to create") unless model.is_a? Class
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cave-0.0.1 lib/cave/model_form.rb