我如何在我创建的rails3中优化(重构)这个非基于activerecord的模型。?
application.rb包含:
CS = CloudServers::Connection.new(:username => '<hidden>', :api_key => '<hidden>')
cloudserver.rb(model)包含:
class Cloudserver
# extend ActiveModel::Naming
attr_reader :id
attr_reader :name
attr_reader :image_id
attr_reader :flavor_id
attr_reader :status
attr_reader :progress
attr_reader :host_id
def initialize(id,name,image_id,flavor_id,status,progress,host_id)
@id = id
@name = name
@image_id = image_id
@flavor_id = flavor_id
@status = status
@progres = progress
@host_id = host_id
end
def self.all
server = CS.servers.map { |i|
new(i[:id],i[:name],i[:imageId],i[:flavorId],i[:status],i[:progress],i[:hostId])
# new(i)
}
end
def self.find(param)
all.detect { |l| l.id == param.to_i } || raise(ActiveRecord::RecordNotFound)
end
# def self.new
# server = CS.create_server(:name => "BOOYA", :imageId => 49, :flavorId => 2, :metadata => {'Luke' => 'Awesome'})
# end
end
仅供参考我正在尝试为此api构建rails模型: https://github.com/rackspace/ruby-cloudservers
我应该打扰还是只让控制器直接访问CS对象
答案 0 :(得分:1)
仅仅为了重构,这是编写同一个类的简短方法
class Cloudserver < Struct.new(:id, :name, :image_id, :flavor_id, :status, :progress, :host_id)
class << self
def all
server = CS.servers.map { |i|
new(i[:id],i[:name],i[:imageId],i[:flavorId],i[:status],i[:progress],i[:hostId])
}
end
def find
all.detect { |l| l.id == param.to_i } || raise(ActiveRecord::RecordNotFound)
end
end
end