Sha256: 9a17d23a6cf2e45bc6ab5bdaba4e2b98546f7c1e0bab18b281f4d34ce142676e

Contents?: true

Size: 1.51 KB

Versions: 7

Compression:

Stored size: 1.51 KB

Contents

module JsonApiClient
  module Helpers
    module DynamicAttributes

      def attributes
        @attributes
      end

      def attributes=(attrs = {})
        @attributes ||= ActiveSupport::HashWithIndifferentAccess.new

        return @attributes unless attrs.present?
        attrs.each do |key, value|
          send("#{key}=", value)
        end
      end

      def [](key)
        read_attribute(key)
      end

      def []=(key, value)
        set_attribute(key, value)
      end

      def respond_to_missing?(method, include_private = false)
        if (method.to_s =~ /^(.*)=$/) || has_attribute?(method)
          true
        else
          super
        end
      end

      def has_attribute?(attr_name)
        attributes.has_key?(attr_name)
      end

      protected

      def method_missing(method, *args, &block)
        normalized_method = if key_formatter
                              key_formatter.unformat(method.to_s)
                            else
                              method.to_s
                            end

        if normalized_method =~ /^(.*)=$/
          set_attribute($1, args.first)
        elsif has_attribute?(method)
          attributes[method]
        else
          super
        end
      end

      def read_attribute(name)
        attributes.fetch(name, nil)
      end

      def set_attribute(name, value)
        attributes[name] = value
      end

      def key_formatter
        self.class.respond_to?(:key_formatter) && self.class.key_formatter
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
json_api_client-1.5.3 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.5.2 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.5.1 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.5.0 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.4.0 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.3.0 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.2.0 lib/json_api_client/helpers/dynamic_attributes.rb