class BeautydateApi::Object

Attributes

attributes[RW]
errors[RW]
id[RW]

Public Class Methods

new(attributes = {}) click to toggle source
# File lib/beautydate_api/object.rb, line 5
def initialize(attributes = {})
  @unsaved_attributes = Set.new
  set_attributes(attributes)
  extract_id_from_attributes
end

Public Instance Methods

add_accessor(attribute) click to toggle source
# File lib/beautydate_api/object.rb, line 18
def add_accessor(attribute)
  attribute = attribute.to_s
  return if attribute == 'id'

  singleton_class.class_eval do
    # get
    define_method(attribute) do
      attributes[attribute] || attributes[attribute.to_sym]
    end

    # set
    define_method("#{attribute}=") do |value|
      self.attributes[attribute] = value
      self.unsaved_attributes.add(attribute)
    end
  end
end
set_attributes(attributes) click to toggle source
# File lib/beautydate_api/object.rb, line 11
def set_attributes(attributes)
  @attributes = attributes
  @attributes.each do |attribute, value|
    add_accessor(attribute)
  end
end
unsaved_attributes() click to toggle source
# File lib/beautydate_api/object.rb, line 36
def unsaved_attributes
  @unsaved_attributes
end
unsaved_data() click to toggle source
# File lib/beautydate_api/object.rb, line 40
def unsaved_data
  @attributes.select { |key| @unsaved_attributes.include?(key) }
end

Private Instance Methods

extract_id_from_attributes() click to toggle source
# File lib/beautydate_api/object.rb, line 46
def extract_id_from_attributes
  @id = @attributes&.delete(:id) || @attributes&.delete('id')
end
update_attributes_from_result(result) click to toggle source
# File lib/beautydate_api/object.rb, line 50
def update_attributes_from_result(result)
  set_attributes(result.dig('data', 'attributes'))
  @id = result.dig('data', 'id')
end