Sha256: d9772c8831c8c95c45f83e8ce883701864304e51e3409334b65174a56be11cdf

Contents?: true

Size: 1.38 KB

Versions: 7

Compression:

Stored size: 1.38 KB

Contents

module CouchTomato
  module Persistence
    class BelongsToProperty #:nodoc:
      attr_accessor :name
      
      def initialize(owner_clazz, name, options = {})
        self.name = name
        accessors =  <<-ACCESSORS
          def #{name}
            return @#{name} if instance_variable_defined?(:@#{name})
            @#{name} = @#{name}_id ? #{item_class_name}.find(@#{name}_id) : nil
          end
          
          def #{name}=(value)
            @#{name} = value
            if value.nil?
              @#{name}_id = nil
            else
              @#{name}_id = value.id
            end
          end
          
          def #{name}_id=(id)
            remove_instance_variable(:@#{name}) if instance_variable_defined?(:@#{name})
            @#{name}_id = id
          end
        ACCESSORS
        owner_clazz.class_eval accessors
        owner_clazz.send :attr_reader, "#{name}_id"
      end
      
      # def save(object)
      #   
      # end
      
      def dirty?(object)
        false
      end
      
      # def destroy(object)
      #   
      # end
      
      def build(object, json)
        object.send "#{name}_id=", json["#{name}_id"]
      end
      
      def serialize(json, object)
        json["#{name}_id"] = object.send("#{name}_id") if object.send("#{name}_id")
      end
      
      def item_class_name
        @name.to_s.camelize
      end
      
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
couch_tomato-0.2.0 lib/couch_tomato/persistence/belongs_to_property.rb
couch_tomato-0.1.5 lib/couch_tomato/persistence/belongs_to_property.rb
couch_tomato-0.1.4 lib/couch_tomato/persistence/belongs_to_property.rb
couch_tomato-0.1.3 lib/couch_tomato/persistence/belongs_to_property.rb
couch_tomato-0.1.2 lib/couch_tomato/persistence/belongs_to_property.rb
couch_tomato-0.1.1 lib/couch_tomato/persistence/belongs_to_property.rb
couch_tomato-0.1.0 lib/couch_tomato/persistence/belongs_to_property.rb