Class: RightResource::Base

Inherits:
Object show all
Defined in:
lib/right_resource/base.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) {|_self| ... } ⇒ Base

Returns a new instance of Base.

Yields:

  • (_self)

Yield Parameters:



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/right_resource/base.rb', line 255

def initialize(attributes={})
  # sub-resource4json's key name contains '-'
#      attrs = generate_attributes(attributes)
  @attributes = {}
  loads(attributes)
  if @attributes
    if self.class.resource_id.nil?
      @id = @attributes[:href].match(/\d+$/).to_s if @attributes[:href]
    else
      @id = self.class.resource_id
    end
    load_accessor(@attributes)
  end
  yield self if block_given?
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



270
271
272
# File 'lib/right_resource/base.rb', line 270

def attributes
  @attributes
end

#idObject

Returns the value of attribute id.



270
271
272
# File 'lib/right_resource/base.rb', line 270

def id
  @id
end

Class Method Details

.collection_path(prefix_options = nil, query_options = nil) ⇒ Object

Get resource collections



194
195
196
# File 'lib/right_resource/base.rb', line 194

def collection_path(prefix_options = nil, query_options = nil)
  "#{resource_name}s#{prefix(prefix_options)}.#{format.extension}#{query_string(query_options)}"
end

.connectionObject

Get RESTFul client for HTTP Methods(Low level) and use in resource api call

Examples

conn = Server.connection
conn.get("servers?filter=nickname=server1")

ex. resource api call:

Server.index # => GET /api/acct/1/servers.json


44
45
46
47
48
49
50
51
# File 'lib/right_resource/base.rb', line 44

def connection
  if defined?(@connection) || superclass == Object
    raise ArgumentError, "Not set connection object!!" unless @connection
    @connection
  else
    superclass.connection
  end
end

.connection=(conn) ⇒ Object

Set RESTFul client with login authentication for HTTP Methods(Low level)

Examples

conn = Connection.new do |c|
  c.(:username => "user", :password => "pass", :account => "1")
end
Deployment.connection = conn
Deployment.show(1)  # => GET /api/acct/1/deployments/1.json

RightResource::Base.connction = conn
Ec2EbsVolume.show(1)  # => GET /api/acct/1/ec2_ebs_volumes/1.json
Server.index


32
33
34
# File 'lib/right_resource/base.rb', line 32

def connection=(conn)
  @connection = conn
end

.create(params = {}) ⇒ Object

Create new resource Example:

params = {
  :nickname => "dev",
  :deployment_href => "https://my.rightscale.com/api/acct/22329/deployments/59855",
  :server_template_href => "https://my.rightscale.com/api/acct/22329/server_templates/76610",
  :ec2_availability_zone => "ap-northeast-1a"
}
Server.create(params)


161
162
163
164
165
166
167
168
# File 'lib/right_resource/base.rb', line 161

def create(params={})
  #TODO: refactor
  self.new(params).tap do |resource|
    resource.save
  end
#        path = collection_path
#        connection.post(path, params)
end

.destory(id) ⇒ Object

Delete resource Example:

Server.destory(1)

server = Server.index(:filter => "aws_id=i-012345")
Server.destory(server.id)


183
184
185
186
# File 'lib/right_resource/base.rb', line 183

def destory(id)
  path = element_path(id)
  connection.delete(path)
end

.element_path(id, prefix_options = nil, query_options = nil) ⇒ Object

Get single resource



189
190
191
# File 'lib/right_resource/base.rb', line 189

def element_path(id, prefix_options = nil, query_options = nil)
  "#{resource_name}s/#{id}#{prefix(prefix_options)}.#{format.extension}#{query_string(query_options)}"
end

.formatObject

Get request and response format type object



67
68
69
# File 'lib/right_resource/base.rb', line 67

def format
  connection.format || RightResource::Formats::JsonFormat
end

.format=(mime_type_reference_or_format) ⇒ Object

Sets the format that attributes are sent and received in from a mime type reference:

Examples

Server.format = RightResource::Formats::JsonFormat
Server.show(1) # => GET /api/acct/1/servers/1.json

RightResource::Base.format = RightResource::Formats::JsonFormat
Server.index # => GET /api/acct/1/servers.json
Ec2EbsVolume.index # => GET /api/acct/1/ec2_ebs_volumes.json


62
63
64
# File 'lib/right_resource/base.rb', line 62

def format=(mime_type_reference_or_format)
  connection.format = mime_type_reference_or_format
end

.generate_attributes(attributes) ⇒ Object

Raises:

  • (ArgumentError)


211
212
213
214
215
216
# File 'lib/right_resource/base.rb', line 211

def generate_attributes(attributes)
  raise ArgumentError, "expected an attributes Hash, got #{attributes.pretty_inspect}" unless attributes.is_a?(Hash)
  attrs = {}
  attributes.each_pair {|key,value| attrs[key.to_s.gsub('-', '_').to_sym] = value}
  attrs
end

.headersObject

Get response headers via RESTFul client



72
73
74
# File 'lib/right_resource/base.rb', line 72

def headers
  connection.headers || {}
end

.index(params = {}) ⇒ Object

Get resources by index method same resources support criteria like filtering.

Params

params

criteria[ex. :filter => “nickname=hoge”](Hash)

Return

Resource list(Array)

Examples

dep = Deployment.index(:filter => ["nickname=payment-dev", "nickname=payment-staging"])

test = Server.index(:filter => "nickname<>test")

Criteria unsupport

array = ServerArray.index

Get first 5 resources

server = Server.index.first(5) # see Array class

Get last resource

server = Server.index.last # see Array class

Get all operational server’s nickname

Server.index.each do |server|
  puts server.nickname if server.state = "operational"
end

Get EC2 Security Groups(aws ap = 4)

sec_grps = Ec2SecurityGroup.index(:cloud_id => "4")


114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/right_resource/base.rb', line 114

def index(params = {})
  path = "#{resource_name}s.#{format.extension}#{query_string(params)}"
  connection.clear
  instantiate_collection(format.decode(connection.get(path || [])))
rescue RestClient::ResourceNotFound
  nil
rescue => e
  logger.error("#{e.class}: #{e.pretty_inspect}")
  logger.debug {"Backtrace:\n#{e.backtrace.pretty_inspect}"}
ensure
  logger.debug {"#{__FILE__} #{__LINE__}: #{self.class}\n#{self.pretty_inspect}\n"}
end

.loggerObject



13
14
15
16
17
18
19
# File 'lib/right_resource/base.rb', line 13

def logger
  if defined?(@logger) || superclass == Object
    @logger ||= Logger.new(STDERR).tap {|l| l.level = Logger::WARN}
  else
    superclass.logger
  end
end

.logger=(logger) ⇒ Object

Set Logger object

Examples

logger = Logger.new(STDERR)
logger.level = Logger::WARN [Default: Logger::DEBUG]
Server.logger = logger


9
10
11
# File 'lib/right_resource/base.rb', line 9

def logger=(logger)
  @logger = logger
end

.resource_idObject

Get resource id in response location header via RESTFul client(create only?)



82
83
84
# File 'lib/right_resource/base.rb', line 82

def resource_id
  connection.resource_id || nil
end

.resource_nameObject

Get resource name(equals plural of classname)



199
200
201
202
203
204
205
206
207
208
209
# File 'lib/right_resource/base.rb', line 199

def resource_name
  name = ""
  self.name.to_s.split(/::/).last.scan(/([A-Z][^A-Z]*)/).flatten.each_with_index do |str,i|
    if i > 0
      name << "_#{str.downcase}"
    else
      name << str.downcase
    end
  end
  name
end

.show(id, params = {}) ⇒ Object

Get resource

Params

params

Query Strings(Hash)

Return

Resource(Object)

Example

server_id = 1
Server.show(server_id) #=> #<Server:0x1234...>

Get deployment resource with server’s subresource

Deployment.show(1, :params => {:server_settings => "true"}) #=> #<Deployment:0x12314...>


139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/right_resource/base.rb', line 139

def show(id, params = {})
  path = element_path(id, nil, params)
  connection.clear
  instantiate_record(format.decode(connection.get(path)))
rescue RestClient::ResourceNotFound
  nil
rescue => e
  logger.error("#{e.class}: #{e.pretty_inspect}")
  logger.debug {"Backtrace:\n#{e.backtrace.pretty_inspect}"}
ensure
  logger.debug {"#{__FILE__} #{__LINE__}: #{self.class}\n#{self.pretty_inspect}\n"}
end

.statusObject

Get response status code



77
78
79
# File 'lib/right_resource/base.rb', line 77

def status
  connection.status || nil
end

.update(id, params = {}) ⇒ Object

Update resource



171
172
173
174
175
# File 'lib/right_resource/base.rb', line 171

def update(id, params={})
  #TODO: refactor
  path = element_path(id)
  connection.put(path, params)
end

Instance Method Details

#destoryObject



306
307
308
# File 'lib/right_resource/base.rb', line 306

def destory
  connection.delete(element_path)
end

#load_accessor(attributes) ⇒ Object

Raises:

  • (ArgumentError)


282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/right_resource/base.rb', line 282

def load_accessor(attributes)
  raise ArgumentError, "expected an attributes Hash, got #{attributes.pretty_inspect}" unless attributes.is_a?(Hash)
  attributes.each_pair do |key, value|
    instance_variable_set("@#{key}", value) # Initialize instance variables
    self.class.class_eval do
      define_method("#{key}=") do |new_value| # ex. obj.key = new_value
        instance_variable_set("@#{key}", new_value)
      end
      define_method(key) do
        instance_variable_get("@#{key}")
      end
    end
  end
end

#loads(attributes) ⇒ Object

Raises:

  • (ArgumentError)


272
273
274
275
276
# File 'lib/right_resource/base.rb', line 272

def loads(attributes)
  raise ArgumentError, "expected an attributes Hash, got #{attributes.pretty_inspect}" unless attributes.is_a?(Hash)
  attributes.each_pair {|key,value| @attributes[key.to_s.gsub('-', '_').to_sym] = value}
  self
end

#new?Boolean Also known as: new_record?

Returns:

  • (Boolean)


297
298
299
# File 'lib/right_resource/base.rb', line 297

def new?
  id.nil?
end

#saveObject



302
303
304
# File 'lib/right_resource/base.rb', line 302

def save
  new? ? create : update
end

#update_attributes(attributes) ⇒ Object



278
279
280
# File 'lib/right_resource/base.rb', line 278

def update_attributes(attributes)
  loads(attributes) && load_accessor(attributes) && save
end