Sha256: d232c3e7c280d7d407f74c1ad9d667c90379cbd968a44ba5000bb4dcc4d6c858

Contents?: true

Size: 1003 Bytes

Versions: 2

Compression:

Stored size: 1003 Bytes

Contents

module Bright
  class Model
    @attribute_names = []

    def initialize(attributes = {})
      assign_attributes(attributes) if attributes

      super()
    end

    def assign_attributes(new_attributes)
      if !new_attributes.is_a?(Hash)
        raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
      end
      return if new_attributes.empty?

      attributes = new_attributes.collect { |k, v| [k.to_sym, v] }.to_h
      _assign_attributes(attributes)
    end

    def self.attribute_names
      @attribute_names
    end

    def to_json
      self.class.attribute_names.collect do |n|
        [n, send(n)]
      end.to_h.to_json
    end

    private

    def _assign_attributes(attributes)
      attributes.each do |k, v|
        _assign_attribute(k, v)
      end
    end

    def _assign_attribute(k, v)
      if respond_to?(:"#{k}=")
        public_send(:"#{k}=", v)
      else
        raise UnknownAttributeError.new(self, k)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bright-2.1 lib/bright/model.rb
bright-2.0 lib/bright/model.rb