Module: JsonObject

Included in:
Base, JsonOpenStruct
Defined in:
lib/json_object.rb,
lib/json_object/version.rb

Overview

The intended use of this module is for inclusion in a class, there by giving the class the necessary methods to store a JSON Hash and define custom accessors to retrieve its values.

Examples:

when including class has a no argument initializer

class SomeClass
  include JsonObject
end

when the including class has an initializer with arguments

class AnotherClass
  include JsonObject

  def initialize string
    # does something with string
  end

  # we must override the default {#create} method as it will call
  # new() with no arguments on the class by default

  #this is the form it must take
  def self.create hash, parent=nil
    # here we imagine getting the initializer string param from the hash
    obj = new(hash["..."])

    # we must set the json_hash instance variable for proper functionality
    obj.json_hash = hash

    # optionally we can set the hash_parent variable
    obj.parent = parent

    #finnally we return our new object
    obj
  end

  # same as above but using Object#tap for a cleaner implementation
  def self.create hash, parent=nil
    new(hash["..."]).tap do |obj|
      obj.json_hash = hash
      obj.parent = parent
    end
  end

end

Defined Under Namespace

Modules: ClassMethods Classes: Base, JsonOpenStruct

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#json_hashObject

Stores the underlying JSON Hash that we wish to then declare accessors for.



99
100
101
# File 'lib/json_object.rb', line 99

def json_hash
  @json_hash
end

#parentObject

Used to aid in nested JsonObject’s traversing back through their parents.



96
97
98
# File 'lib/json_object.rb', line 96

def parent
  @parent
end

Class Method Details

.createObject



82
83
84
# File 'lib/json_object.rb', line 82

def create
  Class.new.include(JsonObject)
end

.default_json_object_classObject

Retrieve a set default class or use our JsonOpenStruct default.



78
79
80
# File 'lib/json_object.rb', line 78

def default_json_object_class
  @default_json_object_class || JsonObject::JsonOpenStruct
end

.default_json_object_class=(klass) ⇒ Object

Allows setting a custom class to replace the default JsonOpenStruct.



73
74
75
# File 'lib/json_object.rb', line 73

def default_json_object_class= klass
  @default_json_object_class = klass
end

.included(klass) ⇒ Object

Callback runs when module is included in another module/class.

We use this to automatically extend our ClassMethods module in a class that includes JsonObject.



91
92
93
# File 'lib/json_object.rb', line 91

def self.included klass
  klass.extend ClassMethods
end