Class: JSONAPI::NameValuePair

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

Overview

A generic name->value query pair

Instance Attribute Summary

Attributes inherited from Item

#item

Instance Method Summary collapse

Constructor Details

#initialize(name, value) ⇒ NameValuePair

Returns a new instance of NameValuePair.

Parameters:

  • name

    The name of the pair

  • value

    The value of the pair



12
13
14
15
# File 'lib/easy/jsonapi/name_value_pair.rb', line 12

def initialize(name, value)
  name = name.to_s.gsub('-', '_')
  super({ name: name.to_s, value: value })
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class JSONAPI::Item

Instance Method Details

#nameString

Returns The name of the name->val pair.

Returns:

  • (String)

    The name of the name->val pair



18
19
20
# File 'lib/easy/jsonapi/name_value_pair.rb', line 18

def name
  @item[:name]
end

#name=(_) ⇒ Object

Raises:

  • RunTimeError You shouldn’t be able to update the name of a NameValuePair



24
25
26
# File 'lib/easy/jsonapi/name_value_pair.rb', line 24

def name=(_)
  raise 'Cannot change the name of NameValuePair Objects'
end

#to_hObject

Represents a pair as a hash



65
66
67
# File 'lib/easy/jsonapi/name_value_pair.rb', line 65

def to_h
  { name.to_sym => JSONAPI::Utility.to_h_value(value) }
end

#to_sObject

Represents a pair as a string



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/easy/jsonapi/name_value_pair.rb', line 39

def to_s
  v = value
  val_str = case v
            when Array
              val_str = '['
              first = true
              v.each do |val|
                if first
                  val_str += "\"#{val}\""
                  first = false
                else
                  val_str += ", \"#{val}\""
                end
              end
              val_str += ']'
            when String
              "\"#{v}\""
            when JSONAPI::NameValuePair
              "{ #{v} }"
            else
              v
            end
  "\"#{name}\": #{val_str}"
end

#valueString

Returns The value of the name->val pair.

Returns:

  • (String)

    The value of the name->val pair



29
30
31
# File 'lib/easy/jsonapi/name_value_pair.rb', line 29

def value
  @item[:value]
end

#value=(new_value) ⇒ Object

Parameters:

  • new_value (String | Symbol)

    The name->val pair value



34
35
36
# File 'lib/easy/jsonapi/name_value_pair.rb', line 34

def value=(new_value)
  @item[:value] = new_value
end