Module: X::Resources::Serialization

Included in:
MatchingRule, PersonalizedTrend, PostUsage, X::Resource, Trend
Defined in:
x-resources/lib/x/resources/serialization.rb

Overview

Serialization of what an API response held, by its attributes alone

ActiveSupport's Object#as_json would otherwise read the instance variables, which hold the client and so its credentials, and loop for good once a reference has resolved.

Internal to x-resources: the methods it gives a resource, X::PostUsage, and the other values of the object layer, such as to_json, are public API, but the module is only how they are shared, and which classes extend or include it can change within 1.x.

Instance Method Summary collapse

Instance Method Details

#as_json ⇒ Hash{String => Object}

The attributes, as a JSON encoder and ActiveSupport read them

Examples:

Serialize a resource

user.as_json # => {"id" => "7505382", "username" => "sferik"}

Serialize a problem

problem.as_json # => {"title" => "Not Found Error"}

Returns:

  • (Hash{String => Object}) —

    the attributes



43
# File 'x-resources/lib/x/resources/serialization.rb', line 43

def as_json(*) = attrs

#to_h {|key, value| ... } ⇒ Hash

The attributes, or with a block the Hash of the pairs it returns for them

With a block it is the to_h of the attributes, as a Hash builds it, rather than the attributes, the block ignored.

Examples:

Convert a resource to a hash

user.to_h # => {"id" => "7505382", "username" => "sferik"}

Key the attributes by Symbol

user.to_h { |key, value| [key.to_sym, value] } # => {id: "7505382", username: "sferik"}

Delete the rule a post matched

streaming_client.delete_rules(post.matching_rules.first.to_h)

Yield Parameters:

  • key (String) —

    the name of each attribute

  • value (Object) —

    its value

Yield Returns:

  • (Array(Object, Object)) —

    the key and value of the attribute in the Hash

Returns:

  • (Hash) —

    the attributes, frozen, or the pairs the block returns



33
# File 'x-resources/lib/x/resources/serialization.rb', line 33

def to_h(&) = attrs.to_h(&) # steep:ignore BlockTypeMismatch

#to_json(state = nil) ⇒ String

The attributes as JSON

Examples:

Serialize a resource

user.to_json # => "{\"id\":\"7505382\",\"username\":\"sferik\"}"

Cache a resource as JSON

Rails.cache.write("user", user.to_json)

Parameters:

  • state (JSON::State, nil) (defaults to: nil) —

    the state a JSON encoder passes, which the attributes are given

Returns:

  • (String) —

    the attributes as a JSON object



54
# File 'x-resources/lib/x/resources/serialization.rb', line 54

def to_json(state = nil) = as_json.to_json(state)