Class: JSONAPI::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/easy/jsonapi/item.rb

Overview

Models a Item’s key -> value relationship

Direct Known Subclasses

Field, NameValuePair

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ Item

Able to take a hash and dynamically create instance variables using the hash keys

Ex: obj == { :name => 'fields', :value => {'articles' => 'title,body,author', 'people' => 'name' }}

Parameters:

  • obj (Object)

    Can be anything, but if a hash is provided, dynamic instance variable can be created upon trying to access them.



15
16
17
18
19
20
# File 'lib/easy/jsonapi/item.rb', line 15

def initialize(obj)
  if obj.is_a? Hash
    ensure_keys_are_sym(obj)
  end
  @item = obj
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object (private)

Only used if implementing Item directly.

dynamically creates accessor methods for instance variables
created in the initialize


48
49
50
51
52
53
54
55
56
57
58
# File 'lib/easy/jsonapi/item.rb', line 48

def method_missing(method_name, *args, &block)
  return super unless is_a? JSONAPI::Item
  return super unless @item.is_a? Hash
  if should_update_var?(method_name)
    @item[method_name[0..-2].to_sym] = args[0]
  elsif should_get_var?(method_name)
    @item[method_name]
  else
    super
  end
end

Instance Attribute Details

#itemObject

Returns the value of an Item.

Returns:

  • the value of an Item



9
10
11
# File 'lib/easy/jsonapi/item.rb', line 9

def item
  @item
end

Instance Method Details

#to_hObject

Represent item as a hash



39
40
41
# File 'lib/easy/jsonapi/item.rb', line 39

def to_h
  @item.to_h
end

#to_sObject

A special to_string method if @item is a hash.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/easy/jsonapi/item.rb', line 23

def to_s
  return @item.to_s unless @item.is_a? Hash
  tr = '{ '
  first = true
  @item.each do |k, v|
    if first
      first = false
      tr += "\"#{k}\": \"#{v}\", "
    else
      tr += "\"#{k}\": \"#{v}\""
    end
  end
  tr += ' }'
end