Class: RubyBox::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby-box/item.rb

Constant Summary collapse

@@has_many =
[]
@@has_many_paginated =
[]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(session, raw_item) ⇒ Item

Returns a new instance of Item.



9
10
11
12
# File 'lib/ruby-box/item.rb', line 9

def initialize( session, raw_item )
  @session = session
  @raw_item = raw_item
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/ruby-box/item.rb', line 49

def method_missing(method, *args, &block)
  key = method.to_s

  # Support has many and paginated has many relationships.
  return many(key) if @@has_many.include?(key)
  return paginated(key, args[0] || 100, args[1] || 0) if @@has_many_paginated.include?(key)
  
  # update @raw_item hash if this appears to be a setter.
  setter = method.to_s.end_with?('=')
  key = key[0...-1] if setter
  @raw_item[key] = args[0] if setter and update_fields.include?(key)
  
  # we may have a mini version of the object loaded, fix this.
  reload_meta if @raw_item[key].nil? and has_mini_format?

  if @raw_item[key].kind_of?(Hash)
    return RubyBox::Item.factory(@session, @raw_item[key])
  elsif RubyBox::ISO_8601_TEST.match(@raw_item[key].to_s)
    return Time.parse(@raw_item[key])
  else
    return @raw_item[key]
  end
end

Class Method Details

.has_many(*keys) ⇒ Object



14
15
16
# File 'lib/ruby-box/item.rb', line 14

def self.has_many(*keys)
  keys.each {|key| @@has_many << key.to_s}
end

.has_many_paginated(*keys) ⇒ Object



18
19
20
# File 'lib/ruby-box/item.rb', line 18

def self.has_many_paginated(*keys)
  keys.each {|key| @@has_many_paginated << key.to_s}
end

Instance Method Details

#deleteObject



38
39
40
41
# File 'lib/ruby-box/item.rb', line 38

def delete
  url = "#{RubyBox::API_URL}/#{resource_name}/#{id}"
  resp = @session.delete( url )
end

#reload_metaObject



43
44
45
46
47
# File 'lib/ruby-box/item.rb', line 43

def reload_meta
  url = "#{RubyBox::API_URL}/#{resource_name}/#{@raw_item['id']}"
  @raw_item = @session.get( url )
  self
end

#updateObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ruby-box/item.rb', line 22

def update
  reload_meta unless etag

  url = "#{RubyBox::API_URL}/#{resource_name}/#{id}"
  uri = URI.parse(url)

  request = Net::HTTP::Put.new(uri.path, {
    "if-match" => etag,
    "Content-Type" => 'application/json'
  })
  request.body = JSON.dump(serialize)

  @raw_item = @session.request(uri, request)
  self
end