Sha256: ef04ff81092e336b9db82c97d3b57d3172dd2a1f00d802deacd44fa28b162a3a

Contents?: true

Size: 1.33 KB

Versions: 4

Compression:

Stored size: 1.33 KB

Contents

module CleanModel
  module Base

    def self.included(base)
      base.send :extend, ClassMethods
      base.send :include, InstanceMethods
      base.send :extend, ActiveModel::Translation
      base.send :include, ActiveModel::Validations
    end

    module ClassMethods

      def attribute(name, options={})
        attr = Attribute.new(name, options)
        attributes << attr

        define_method name do
          instance_variable_get "@#{name}"
        end

        define_method "#{name}=" do |value|
          value = attr.transform(value)
          attr.validate!(value)
          instance_variable_set "@#{name}", value
        end
      end

      def attributes
        @attributes ||= []
      end

      def attribute_names
        attributes.map(&:name)
      end

    end

    module InstanceMethods

      def initialize(attributes={})
        self.class.attributes.each { |a| a.assign_default(self) }
        if block_given?
          yield(self)
        else
          assign_attributes attributes
        end
      end

      def assign_attributes(attributes)
        return nil unless attributes
        attributes.each do |name, value|
          send("#{name}=", value) if respond_to?("#{name}=")
        end
      end

      def attributes
        Hash[self.class.attribute_names.map { |a| [a, send(a)] }]
      end

    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
clean_model-0.0.9 lib/clean_model/base.rb
clean_model-0.0.8 lib/clean_model/base.rb
clean_model-0.0.7 lib/clean_model/base.rb
clean_model-0.0.6 lib/clean_model/base.rb