Method: CFoundry::V1::ModelMagic#define_client_methods

Defined in:
lib/cfoundry/v1/model_magic.rb

#define_client_methods(klass = self) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/cfoundry/v1/model_magic.rb', line 33

def define_client_methods(klass = self)
  singular = klass.object_name
  plural = klass.plural_object_name

  base_singular = klass.base_object_name
  base_plural = klass.plural_base_object_name

  on_base_client do
    define_method(base_singular) do |guid|
      get(base_plural, guid, :accept => :json)
    end

    define_method(:"create_#{base_singular}") do |payload|
      post(base_plural, :content => :json, :accept => :json, :payload => payload)
    end

    define_method(:"delete_#{base_singular}") do |guid|
      delete(base_plural, guid)
      true
    end

    define_method(:"update_#{base_singular}") do |guid, payload|
      put(base_plural, guid, :content => :json, :payload => payload)
    end

    define_method(base_plural) do |*args|
      get(base_plural, :accept => :json)
    end
  end

  on_client do
    if klass.guid_name
      define_method(:"#{singular}_by_#{klass.guid_name}") do |guid|
        obj = send(singular, guid)
        obj if obj.exists?
      end
    end

    define_method(singular) do |*args|
      guid, _ = args
      klass.new(guid, self)
    end

    define_method(plural) do |*args|
      options, _ = args
      options ||= {}

      @base.send(base_plural).collect do |json|
        klass.new(json[klass.guid_name], self, json)
      end
    end
  end
end