Sha256: 8de889dd4e493e1776b6c12563272ccd69f6b85314d8f6937d13fbff09d1552f

Contents?: true

Size: 1.45 KB

Versions: 8

Compression:

Stored size: 1.45 KB

Contents

class LogicalModel
  module Attributes
    # TODO replace this module with ActvieAttr ?
    def self.included(base)
      base.send(:include, InstanceMethods)
      base.send(:extend, ClassMethods)
    end

    module InstanceMethods

      def attributes=(attrs)
        attrs.each{|k,v| send("#{k}=",v) if respond_to?("#{k}=")}
      end

      def attributes
        attrs = self.class.attribute_keys.inject(ActiveSupport::HashWithIndifferentAccess.new) do |result,key|
          result[key] = read_attribute_for_validation(key)
          result
        end

        unless self.class.has_many_keys.blank?
          self.class.has_many_keys.inject(attrs) do |result,key|
            result["#{key}_attributes"] = send(key).map {|a| a.attributes}
            result
          end
        end
        attrs.reject {|key, value| key == "_id" && value.blank?}
      end
    end

    module ClassMethods

      # declares an attribute.
      # @param name [Symbol]
      # @example
      #     class Client < LogicalModel
      #       attribute :att_name
      #     end
      def attribute(name)
        @attribute_keys = [] if @attribute_keys.nil?
        @attribute_keys << name
        attr_accessor name
      end

      # overrides attributes with given keys.
      # @param keys [Array<Symbol>]
      def attribute_keys=(keys)
        @attribute_keys = keys
        attr_accessor *keys
      end

      def attribute_keys
        @attribute_keys
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
logical_model-0.7.6 lib/logical_model/attributes.rb
logical_model-0.7.5 lib/logical_model/attributes.rb
logical_model-0.7.4 lib/logical_model/attributes.rb
logical_model-0.7.3 lib/logical_model/attributes.rb
logical_model-0.7.2 lib/logical_model/attributes.rb
logical_model-0.7.1 lib/logical_model/attributes.rb
logical_model-0.7.0 lib/logical_model/attributes.rb
logical_model-0.6.6 lib/logical_model/attributes.rb