Module: Harpy::Resource::InstanceMethods

Defined in:
lib/harpy/resource.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object (private)



223
224
225
226
227
228
229
230
231
232
# File 'lib/harpy/resource.rb', line 223

def method_missing(method, *args)
  key = method.to_s
  if persisted? && !@attrs.has_key?(key)
    super
  elsif key=~/[\]=]\z/
    super
  else
    @attrs[key]
  end
end

Instance Method Details

#as_json(*args) ⇒ Object



134
135
136
137
138
139
# File 'lib/harpy/resource.rb', line 134

def as_json(*args)
  hash = @attrs.dup
  hash.delete "link"
  hash.delete "urn"
  hash
end

#attributes=(attrs) ⇒ Object



130
131
132
# File 'lib/harpy/resource.rb', line 130

def attributes=(attrs)
  @attrs.merge! attrs
end

#destroyObject

Raises:



153
154
155
156
157
158
# File 'lib/harpy/resource.rb', line 153

def destroy
  raise Harpy::UrlRequired unless url
  _run_destroy_callbacks do
    process_response Harpy.client.delete(url), :destroy
  end
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


185
186
187
# File 'lib/harpy/resource.rb', line 185

def has_key?(key)
  @attrs.has_key? key.to_s
end

#idObject



173
174
175
# File 'lib/harpy/resource.rb', line 173

def id
  @attrs["urn"].split(":").last if @attrs["urn"]
end

#initialize(attrs = nil) ⇒ Object



126
127
128
# File 'lib/harpy/resource.rb', line 126

def initialize(attrs = nil)
  @attrs = attrs || {}
end

#inspectObject



181
182
183
# File 'lib/harpy/resource.rb', line 181

def inspect
  "<#{self.class.name} @attrs:#{@attrs.inspect} @errors:#{errors.inspect} persisted:#{persisted?}>"
end


160
161
162
163
# File 'lib/harpy/resource.rb', line 160

def link(rel)
  link = (@attrs["link"]||[]).detect{|l| l["rel"]==rel.to_s}
  link["href"] if link
end

#persisted?Boolean

Returns:

  • (Boolean)


177
178
179
# File 'lib/harpy/resource.rb', line 177

def persisted?
  @attrs["urn"].present?
end

#saveObject



141
142
143
144
145
146
147
148
149
150
151
# File 'lib/harpy/resource.rb', line 141

def save
  if valid?
    _run_save_callbacks do
      json = Yajl::Encoder.encode as_json
      raise BodyToBig, "Size: #{json.bytesize} bytes (max 1MB)" if json.bytesize > 1.megabyte
      persisted? ? update(json) : create(json)
    end
  else
    false
  end
end

#urlObject



165
166
167
# File 'lib/harpy/resource.rb', line 165

def url
  link "self"
end

#url_collectionObject



169
170
171
# File 'lib/harpy/resource.rb', line 169

def url_collection
  Harpy.entry_point.resource_url self.class.resource_name
end