Sha256: 8fed10a489cf96bc38e4d6d341bab5825fc02528a06926e94d14a2e747b4df55

Contents?: true

Size: 1.26 KB

Versions: 8

Compression:

Stored size: 1.26 KB

Contents

module Restly::Base::Instance::WriteCallbacks
  extend ActiveSupport::Concern

  included do
    before_save :format_request
  end

  private

  def format_request
    @request_body = case format.to_sym
                      when :json
                        savable_resource.to_json
                      when :xml
                        savable_resource.to_xml
                      else
                        savable_resource.to_param
                    end
  end

  def savable_resource
    {resource_name => attributes_with_present_values(writable_attributes)}
  end

  def attributes_with_present_values(attributes=self.attributes)
    attributes.as_json.reduce({}) do |hash, (key, val)|
      if val.is_a?(Hash)
        hash[key] = attributes_with_present_values(val)
      elsif val.present? && key.to_sym != :id
        hash[key] = val
      end
      hash
    end
  end

  def writable_attributes(attributes=self.attributes)
    maa = mass_assignment_authorizer(:default)

    if maa.is_a? ActiveModel::MassAssignmentSecurity::BlackList
      attributes.reject{ |key, val| maa.map(&:to_sym).include?(key.to_sym) }

    elsif maa.is_a? ActiveModel::MassAssignmentSecurity::WhiteList
      attributes.select{ |key, val| maa.map(&:to_sym).include?(key.to_sym) }

    end
  end


end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
restly-0.0.1.beta.3 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.beta.2 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.beta.1 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.alpha.22 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.alpha.19 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.alpha.18 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.alpha.16 lib/restly/base/instance/write_callbacks.rb
restly-0.0.1.alpha.12 lib/restly/base/instance/write_callbacks.rb