class HOALife::Resource

:nodoc

Attributes

base_path[RW]

Public Class Methods

new(obj = {}, relationships = {}) click to toggle source
Calls superclass method
# File lib/hoalife/resource.rb, line 17
def new(obj = {}, relationships = {})
  return super(obj, relationships) unless obj['type']

  camelized = HOALInflector.new.camelize(obj['type'], nil)

  begin
    klass = Object.const_get("HOALife::#{camelized}")
  rescue NameError
    raise HOALife::UndefinedResourceError,
          "HOALife::#{camelized} is not defined"
  end

  klass.new(obj['attributes'], obj['relationships'])
end
new(obj = {}, _relationships = {}) click to toggle source
Calls superclass method
# File lib/hoalife/resource.rb, line 39
def initialize(obj = {}, _relationships = {})
  @obj = cast_attrs(obj)

  super(obj)
end
resource_collection() click to toggle source
# File lib/hoalife/resource.rb, line 32
def resource_collection
  @resource_collection ||= HOALife::Resources::Collection.new(
    HOALife.api_base + base_path
  )
end

Public Instance Methods

as_json() click to toggle source
# File lib/hoalife/resource.rb, line 45
def as_json
  h = {
    'data' => {
      'attributes' => {},
      'relationships' => {}
    }
  }

  each_pair do |k, _v|
    h['data']['attributes'][k] = send(k)
  end

  h
end
to_json(*_args) click to toggle source
# File lib/hoalife/resource.rb, line 60
def to_json(*_args)
  JSON.generate as_json
end

Private Instance Methods

cast_attrs(obj) click to toggle source

rubocop:disable Style/RescueModifier

# File lib/hoalife/resource.rb, line 67
def cast_attrs(obj)
  obj.each do |k, v|
    next unless k.match?(/_at$/)

    time = Time.parse(v) rescue nil
    obj[k] = time if time
  end
end