Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby - dynamically add property to class (at runtime)
    text
    copied!<p>I'm looking for a way to add properties to my already defined class at runtime, or better:</p> <pre><code>class Client attr_accessor :login, :password def initialize args = {} self.login = args[:login] self.password = args[:password] end end </code></pre> <p>But then, I have this hash</p> <pre><code>{:swift_bic=&gt;"XXXX", :account_name=&gt;"XXXX", :id=&gt;"123", :iban=&gt;"XXXX"} </code></pre> <p>and I want this hash to become part of my client instance like</p> <pre><code>client = Client.new :login =&gt; 'user', :password =&gt; 'xxxxx' </code></pre> <p>then with a miraculous magic</p> <pre><code>client @@%$%PLIM!!! {:swift_bic=&gt;"XXXX", :account_name=&gt;"XXXX", :id=&gt;"123", :iban=&gt;"XXXX"} </code></pre> <p>I would be able to access</p> <pre><code>client.swift_bic =&gt; 'XXXX' client.account_name =&gt; 'XXXX' client.id =&gt; 123 </code></pre> <p>and I also would like to maintain a proper object structure like:</p> <pre><code>Client.new(:login =&gt; 'user', :password =&gt; 'xxxxx').inspect #&lt;Client:0x1033c4818 @password='xxxxx', @login='user'&gt; </code></pre> <p>after the magic</p> <pre><code>client.inspect #&lt;Client:0x1033c4818 @password='xxxxx', @login='user', @swift_bic='XXXX', @account_name='XXXX' @id =&gt; '123', @iban =&gt; 'XXXX'&gt; </code></pre> <p>which would give me a very nice and well formatted json after that</p> <p>Is it possible at all?</p> <p>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 :/</p> <p>Thanks chaps.</p> <p>:)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload