Class: HyperResource::Attributes

Inherits:
Hash
  • Object
show all
Defined in:
lib/hyper_resource/attributes.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource = nil) ⇒ Attributes

Returns a new instance of Attributes.



6
7
8
# File 'lib/hyper_resource/attributes.rb', line 6

def initialize(resource=nil)
  self._resource = resource || HyperResource.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/hyper_resource/attributes.rb', line 41

def method_missing(method, *args)
  method = method.to_s
  if self.has_key?(method)
    self[method]
  elsif method[-1,1] == '='
    self[method[0..-2]] = args.first
  else
    raise NoMethodError, "undefined method `#{method}' for #{self.inspect}"
  end
end

Instance Attribute Details

#_resourceObject



4
5
6
# File 'lib/hyper_resource/attributes.rb', line 4

def _resource
  @_resource
end

Instance Method Details

#[](key) ⇒ Object



34
35
36
37
38
# File 'lib/hyper_resource/attributes.rb', line 34

def [](key)
  return super(key.to_s) if self.has_key?(key.to_s)
  return super(key.to_sym) if self.has_key?(key.to_sym)
  nil
end

#[]=(attr, value) ⇒ Object



27
28
29
30
31
# File 'lib/hyper_resource/attributes.rb', line 27

def []=(attr, value)
  return self[attr] if self.has_key?(attr.to_s) && self[attr] == value
  _hr_mark_changed(attr)
  super(attr.to_s, value)
end

#_hr_clear_changedObject



61
62
63
# File 'lib/hyper_resource/attributes.rb', line 61

def _hr_clear_changed # @private
  @_hr_changed = nil
end

#_hr_mark_changed(attr, is_changed = true) ⇒ Object



66
67
68
69
70
# File 'lib/hyper_resource/attributes.rb', line 66

def _hr_mark_changed(attr, is_changed=true)
  attr = attr.to_sym
  @_hr_changed ||= Hash.new(false)
  @_hr_changed[attr] = is_changed
end

#changed?(attr = nil) ⇒ Boolean

Returns true if the given attribute has been changed since creation time, false otherwise. If no attribute is given, return whether any attributes have been changed.

Returns:

  • (Boolean)


14
15
16
17
18
# File 'lib/hyper_resource/attributes.rb', line 14

def changed?(attr=nil)
  @_hr_changed ||= Hash.new(false)
  return @_hr_changed[attr.to_sym] if attr
  return @_hr_changed.keys.count > 0
end

#changed_attributesObject

Returns a hash of the attributes and values which have been changed since creation time.



22
23
24
# File 'lib/hyper_resource/attributes.rb', line 22

def changed_attributes
  @_hr_changed.select{|k,v| v}.keys.inject({}) {|h,k| h[k]=self[k]; h}
end

#respond_to?(method, *args) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
57
58
# File 'lib/hyper_resource/attributes.rb', line 53

def respond_to?(method, *args)
  method = method.to_s
  return true if self.has_key?(method)
  return true if method[-1,1] == '=' && self.has_key?(method[0..-2])
  super
end