Sha256: f02d71667acb5deb5cc7d2dc6a181b2c5a810d4b35c5fa5c579d7436f610f016

Contents?: true

Size: 1.23 KB

Versions: 8

Compression:

Stored size: 1.23 KB

Contents

module JsonApiClient
  module Helpers
    module Attributable
      extend ActiveSupport::Concern

      included do
        attr_reader :attributes
        attr_accessor :errors
        initializer do |obj, params|
          obj.attributes = params
        end
      end

      def attributes=(attrs = {})
        @attributes ||= {}.with_indifferent_access
        @attributes.merge!(attrs)
      end

      def update_attributes(attrs = {})
        self.attributes = attrs
        save
      end

      def method_missing(method, *args, &block)
        if match = method.to_s.match(/^(.*)=$/)
          set_attribute(match[1], args.first)
        elsif has_attribute?(method)
          attributes[method]
        else
          super
        end
      end

      def persisted?
        attributes.has_key?(primary_key)
      end

      def query_params
        attributes.except(primary_key)
      end

      def to_param
        attributes.fetch(primary_key, "").to_s
      end

      protected

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

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

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

    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
json_api_client-0.2.4 lib/json_api_client/helpers/attributable.rb
json_api_client-0.2.3 lib/json_api_client/helpers/attributable.rb
json_api_client-0.2.2 lib/json_api_client/helpers/attributable.rb
json_api_client-0.2.1 lib/json_api_client/helpers/attributable.rb
json_api_client-0.2.0 lib/json_api_client/helpers/attributable.rb
json_api_client-0.1.3 lib/json_api_client/helpers/attributable.rb
json_api_client-0.1.2 lib/json_api_client/helpers/attributable.rb
json_api_client-0.1.1 lib/json_api_client/helpers/attributable.rb