Class: Restfolia::ResourceCreator

Inherits:
Object
  • Object
show all
Defined in:
lib/restfolia/resource_creator.rb

Overview

Public: Factory of Resources. It transforms all JSON objects in Resources.

Examples

factory = Restfolia::ResourceCreator.new
resource = factory.create(:attr_test => "test",
                          :attr_tags => ["tag1", "tag2"],
                          :attr_array_obj => [{:nested => "nested"}],
                          :links => [{:href => "http://service.com",
                                      :rel => "contacts",
                                      :type => "application/json"},
                                     {:href => "http://another.com",
                                      :rel => "relations",
                                      :type => "application/json"}
                                    ])
resource.attr_test  # => "test"
resource.attr_tags  # => ["tag1", "tag2"]
resource.attr_array_obj  # => [#<Restfolia::Resource ...>]

Instance Method Summary collapse

Instance Method Details

#create(json) ⇒ Object

Public: creates Resource looking recursively for JSON objects and transforming in Resources. To create Resource, this method use #resource_class.new(json).

json - Hash parsed from Response body.

Returns Resource from #resource_class. Raises ArgumentError if json is not a Hash.



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/restfolia/resource_creator.rb', line 62

def create(json)
  unless json.is_a?(Hash)
    raise(ArgumentError, "JSON parameter have to be a Hash object", caller)
  end

  json_parsed = {}
  json.each do |attr, value|
    json_parsed[attr] = look_for_resource(value)
  end
  resource_class.new(json_parsed)
end

#resource_classObject

Public: By default, returns Restfolia::Resource. You can use this method to override and returns a custom Resource. See examples.

Examples

# using a custom Resource
class Restfolia::ResourceCreator
  def resource_class
    OpenStruct  #dont forget to require 'ostruct'
  end
end

Returns class of Resource to be constructed.



50
51
52
# File 'lib/restfolia/resource_creator.rb', line 50

def resource_class
  Restfolia::Resource
end