Sha256: fe9dc428b965460434bf433c7fa09d04281474677859791942d4945113d89049

Contents?: true

Size: 1.55 KB

Versions: 3

Compression:

Stored size: 1.55 KB

Contents

module Faceted

  module HasObject

    module ClassMethods

      def fields
        @fields ||= [:id]
      end

      def materialize(objects=[])
        objects.compact.inject([]) do |a, object|
          instance = self.new
          instance.send(:object=, object)
          instance.send(:initialize_with_object)
          a << instance
        end
      end

    end

    # Instance methods =======================================================

    def initialize(args={})
      self.id = args[:id]
      initialize_with_object
      ! args.empty? && args.symbolize_keys.delete_if{|k,v| v.nil?}.each{|k,v| self.send("#{k}=", v) if self.respond_to?("#{k}=") && ! v.blank? }
      self.errors = []
      self.success = true
    end

    def save
      return false unless schema_fields
      schema_fields.each{ |k| object.send("#{k}=", self.send(k)) if object.respond_to?("#{k}=") }
      self.success = object.save
      self.id = object.id
      self.errors = object.errors && object.errors.full_messages
      self.success
    end

    def schema_fields
      self.class.fields
    end

    def to_hash
      schema_fields.inject({}) {|h,k| h[k] = self.send(k); h}
    end

    private

    def initialize_with_object
      return unless object
      schema_fields.each{ |k| self.send("#{k}=", object.send(k)) if self.respond_to?("#{k}=") }
    end

    def object
      return unless self.class.klass
      @object ||= self.id ? self.class.klass.find(self.id) : self.class.klass.new
    end

    def object=(obj)
      @object = obj
      self.id = obj.id
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
faceted-0.8.1 lib/faceted/has_object.rb
faceted-0.8.0 lib/faceted/has_object.rb
faceted-0.7.2 lib/faceted/has_object.rb