【发布时间】:2011-10-06 01:50:44
【问题描述】:
所以这有点傻,更缺乏编程知识,而不是任何 ruby 或 rails 特定的知识。
如果我想把一个普通的类变成哈希,那还不错。我已经有一个了:
class CustomRequest
require 'json'
require 'net/http'
attr_accessor :url, :depth, :status
def initialize(url,depth)
@url = url
@depth = depth
end
def make_me_hash_and_send
@myReq = {:url => @url, :depth =>@depth}
myJsonReq = @myReq
puts myJsonReq
res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3008/user_requests/add.json'),
myJsonReq)
end
end
只需从构造函数中传递的内部变量生成散列。我想对活动记录做同样的事情,但它的抽象性并不容易。
假设我有这门课
def turn_my_insides_to_hash
#How do I take the actual record variables
# nd generate a hash from them.
#Is it something like
@myHash = {:myString = self.myString
:myInt => self.myInt }
end
我可能看错了。我知道在课外我可以简单地说
@x = Result.find(passed_id).to_hash
然后做我想做的事。但我宁愿把东西叫做喜欢
@x = Result.send
(将结果的变量转换为哈希并发送) 我已经有了发送部分,只需要知道如何从类内部将变量转换为哈希。
【问题讨论】:
-
@myHash = self::attributes puts YAML::dump(@myHash)
-
第一个回答的人,我会标记为正确。我正在引用每个参数,甚至不知道属性存在
标签: ruby-on-rails ruby http activerecord hash