Ruby - 动态添加属性到类(在运行时) [英] Ruby - dynamically add property to class (at runtime)
问题描述
我正在寻找一种方法来在运行时为我已经定义的类添加属性,或更好:
attr_accessor:login,:password
def initialize args = {}
self.login = args [:login]
self.password = args [:password]
结束
end
但是,我有这个散列
{:swift_bic =>XXXX,:account_name =>XXXX,:id =>123,:iban => XXXX}
,我希望此哈希成为我的客户端实例
client = Client.new:login => 'user',:password => 'xxxxx'
然后用神奇的魔法
client @@%$%PLIM! {:swift_bic =>XXXX,:account_name =>XXXX,:id =>123,:iban =>XXXX}
pre>
我可以访问
client.swift_bic = > 'XXXX'
client.account_name => 'XXXX'
client.id => 123
,我也想保持一个合适的对象结构,如:
Client.new(:login =>'user',:password =>'xxxxx')inspect
# 0x1033c4818 @ password ='xxxxx',@ login ='user'>
$ bclient.inspect
#< Client:0x1033c4818 @ password ='xxxxx',@ login ='user',@ swift_bic ='XXXX',@ account_name ='XXXX'@id => ; '123',@iban => 'XXXX'>
这将给我一个非常漂亮和格式良好的json之后
这是可能的吗?
我从一个web服务得到这个哈希,所以我不知道是否一个新的属性在那里,然后我将不得不更新我的应用程序,每当他们对他们的服务执行升级。
所以,我想避免这种情况:/
谢谢你们。
: 在添加它们后很多地使用访问器,你可以将它们添加为真正的方法,例如:
class客户端
def add_attrs(attrs)
attrs.each do | var,value |
class_eval {attr_accessor var}
instance_variable_set@#{var},value
end
end
end
这将使它们像普通的实例变量一样工作,但只限于一个
client
。I'm looking for a way to add properties to my already defined class at runtime, or better:
class Client attr_accessor :login, :password def initialize args = {} self.login = args[:login] self.password = args[:password] end end
But then, I have this hash
{:swift_bic=>"XXXX", :account_name=>"XXXX", :id=>"123", :iban=>"XXXX"}
and I want this hash to become part of my client instance like
client = Client.new :login => 'user', :password => 'xxxxx'
then with a miraculous magic
client @@%$%PLIM!!! {:swift_bic=>"XXXX", :account_name=>"XXXX", :id=>"123", :iban=>"XXXX"}
I would be able to access
client.swift_bic => 'XXXX' client.account_name => 'XXXX' client.id => 123
and I also would like to maintain a proper object structure like:
Client.new(:login => 'user', :password => 'xxxxx').inspect #<Client:0x1033c4818 @password='xxxxx', @login='user'>
after the magic
client.inspect #<Client:0x1033c4818 @password='xxxxx', @login='user', @swift_bic='XXXX', @account_name='XXXX' @id => '123', @iban => 'XXXX'>
which would give me a very nice and well formatted json after that
Is it possible at all?
I'm getting this hash from a webservice, so I wouldn't know if theres a new property in there, and then I would have to update my app each time they perform an upgrade on their service. So, I'm sort of trying to avoid this :/
Thanks chaps.
:)
解决方案The
method_missing
approach would work, but if you're going to use the accessors a lot after adding them, you might as well add them as real methods, like this:class Client def add_attrs(attrs) attrs.each do |var, value| class_eval { attr_accessor var } instance_variable_set "@#{var}", value end end end
This will make them work like normal instance variables, but restricted to just one
client
.这篇关于Ruby - 动态添加属性到类(在运行时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!