Sha256: e02f678148faa21294cc71a98ae390b961ea59a7ee57312bcf4670888a7bc2f6

Contents?: true

Size: 1.18 KB

Versions: 4

Compression:

Stored size: 1.18 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|
          set_attribute(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)
        if method.to_s =~ /^(.*)=$/
          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

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
json_api_client-1.0.1 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.0.0 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.0.0.beta7 lib/json_api_client/helpers/dynamic_attributes.rb
json_api_client-1.0.0.beta6 lib/json_api_client/helpers/dynamic_attributes.rb