Sha256: 1b5526f6a728ed9881f9736bf5d03bd13bac40aaaca171090993c13d74a1e880

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

module OptionsModel
  module Concerns
    module AttributeAssignment
      extend ActiveSupport::Concern

      def initialize(attributes = {})
        update_attributes(attributes)
      end

      def initialize_dup(other)
        super

        update_attributes(other)
      end

      def update_attributes(other)
        return unless other

        unless other.respond_to?(:to_h)
          raise ArgumentError, "#{other} must be respond to `to_h`"
        end

        other.to_h.each do |k, v|
          if respond_to?("#{k}=")
            public_send("#{k}=", v)
          else
            unused_attributes[k] = v
          end
        end
      end

      def [](key)
        public_send(key) if respond_to?(key)
      end

      def []=(key, val)
        setter = "#{key}="
        if respond_to?(setter)
          public_send(setter, val)
        else
          unused_attributes[key] = val
        end
      end

      def fetch(key, default = nil)
        if self.class.attribute_names.exclude?(key.to_sym) && default.nil? && !block_given?
          raise KeyError, "attribute not found"
        end

        value = respond_to?(key) ? public_send(key) : nil
        return value if value

        if default
          default
        elsif block_given?
          yield
        end
      end

      def _attributes
        @attributes ||= ActiveSupport::HashWithIndifferentAccess.new
      end
      private :_attributes
      alias_method :attributes, :_attributes

      def _nested_attributes
        @nested_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
      end
      private :_nested_attributes
      alias_method :nested_attributes, :_nested_attributes

      def _unused_attributes
        @unused_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
      end
      private :_unused_attributes
      alias_method :unused_attributes, :_unused_attributes
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
options_model-0.0.3 lib/options_model/concerns/attribute_assignment.rb
options_model-0.0.2 lib/options_model/concerns/attribute_assignment.rb