Module: Protip::Resource

Extended by:
ActiveSupport::Concern
Includes:
ActiveModel::Conversion, ActiveModel::Validations
Defined in:
lib/protip/resource.rb

Defined Under Namespace

Modules: ClassMethods, Creatable, Destroyable, ExtraMethods, SearchMethods, Updatable

Instance Method Summary collapse

Instance Method Details

#attributesObject



290
291
292
293
294
295
296
# File 'lib/protip/resource.rb', line 290

def attributes
  # Like `.as_json`, but includes nil fields to match ActiveRecord behavior.
  self.class.message.descriptor.map{|field| field.name}.inject({}) do |hash, attribute_name|
    hash[attribute_name] = public_send(attribute_name)
    hash
  end
end

#errorsObject



298
299
300
# File 'lib/protip/resource.rb', line 298

def errors
  @errors ||= ActiveModel::Errors.new(self)
end

#initialize(message_or_attributes = {}) ⇒ Object



247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/protip/resource.rb', line 247

def initialize(message_or_attributes = {})
  if self.class.message == nil
    raise RuntimeError.new('Must define a message class using `resource`')
  end
  if message_or_attributes.is_a?(self.class.message)
    self.message = message_or_attributes
  else
    self.message = self.class.message.new
    assign_attributes message_or_attributes
  end

  super()
end

#message=(message) ⇒ Object



261
262
263
# File 'lib/protip/resource.rb', line 261

def message=(message)
  @wrapper = Protip::Wrapper.new(message, self.class.converter)
end

#persisted?Boolean

Returns:

  • (Boolean)


286
287
288
# File 'lib/protip/resource.rb', line 286

def persisted?
  id != nil
end

#saveObject



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/protip/resource.rb', line 265

def save
  success = true
  begin
    if persisted?
      # TODO: use `ActiveModel::Dirty` to only send changed attributes?
      update!
    else
      create!
    end
  rescue Protip::UnprocessableEntityError => error
    success = false
    error.errors.messages.each do |message|
      errors.add :base, message
    end
    error.errors.field_errors.each do |field_error|
      errors.add field_error.field, field_error.message
    end
  end
  success
end