Sha256: e4c1e1a529ae432c6ed256a4b99c61b1faff29ab691a762c415f0aa03d7ab85e

Contents?: true

Size: 1.58 KB

Versions: 9

Compression:

Stored size: 1.58 KB

Contents

# Use this module to add necessary attributes methods that ActiveModel::AttributeMethods doesn't add
# An ATTRIBUTES constant must be on the model before including this module
# Attributes specified in ATTRIBUTES will be serialized if any ActiveModel::Serializers are used
# Any attributes that shouldn't be serialized can still be set with another attr_accessor, but won't show up in
#

module CellSet
  module Attributes
    extend ActiveSupport::Concern
    extend ActiveModel::Naming
    include ActiveModel::AttributeMethods

    included do
      self.send(:attr_accessor, *self::ATTRIBUTES)

      if self.private_methods.include?(:define_attribute_method)
        self.send(:define_attribute_method, self::ATTRIBUTES)
      end
    end

    module ClassMethods
      def human_attribute_name(attr, options = {})
        attr
      end

      def lookup_ancestors
        [self]
      end
    end

    def initialize(attrs = {})
      @errors = ActiveModel::Errors.new(self)
      attrs.each do |name, value|
        send("#{name}=", value) if value
      end
      super(attrs)
    end

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

    def attributes=(attrs)
       attrs.each_pair {|k, v| send("#{k}=", v)}
    end

    def clear_attribute(attr)
      send("#{attr}=", nil)
    end

    def has_attribute?(attr)
      self.class::ATTRIBUTES.include?(attr)
    end

    def read_attribute_for_validation(key)
      send(key)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
cell_set-0.2.3 lib/cell_set/attributes.rb
cell_set-0.2.2 lib/cell_set/attributes.rb
cell_set-0.2.1 lib/cell_set/attributes.rb
cell_set-0.2.0 lib/cell_set/attributes.rb
cell_set-0.1.4 lib/cell_set/attributes.rb
cell_set-0.1.3 lib/cell_set/attributes.rb
cell_set-0.1.2 lib/cell_set/attributes.rb
cell_set-0.1.1 lib/cell_set/attributes.rb
cell_set-0.1.0 lib/cell_set/attributes.rb