module Unchained::Client::Mixins::Resource::ClassMethods

Attributes

attributes[R]

Public Instance Methods

attribute(name, type, opts={}) click to toggle source
# File lib/unchained/client/mixins/resource.rb, line 76
def attribute(name, type, opts={})
  instance_eval do
    attr_accessor name
  end

  @attributes ||= []
  @attributes << Attribute.new(name, type, opts)
end
from_hash(json, client: nil) click to toggle source

This is a pretty naive implementation of parsing JSON. It will loop through all of `@attributes` to find the right one, then do some very minimal validation, before setting the attribute on the instance.

Returns an instance of the class that uses this mixin.

# File lib/unchained/client/mixins/resource.rb, line 91
def from_hash(json, client: nil)
  res = self.new

  json.each do |k, v|
    # TODO: Better way to do this?
    attr = @attributes.find{|a| a.json_field == k.to_s}
    raise InvalidAttribute.new(
      "`#{self.name.split('::').last}` did not define a `#{k}`."
    ) if attr.nil?

    # TODO: Better way to do this?
    case attr.type.to_s
    when Integer.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(Fixnum)
      value = v.to_i
    when Float.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(Float)
      value = v.to_f
    when String.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(String)
      value = v
    when Hash.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(Hash)
      value = v
    end

    # Lurk, there is probably a better way to do this.
    if !attr.expand_method.nil?
      client ||= Unchained::Client.new
      value = client.send(attr.expand_method, value)
    end

    res.send("#{attr.name}=", value)
  end

  res
end

Private Instance Methods

maybe_raise_invalid_value(attribute, key, value) click to toggle source
# File lib/unchained/client/mixins/resource.rb, line 131
def maybe_raise_invalid_value(attribute, key, value)
  if value.nil?
    return if attribute.allow_nil?

    raise InvalidValue.new(
      "`#{attribute.name}` is not allowed to be nil.",
    )
  end

  raise InvalidValue.new(
    "Expected #{attribute.type}, got #{value.class}. `#{key}` (#{value})."
  )
end