试图从ruby中的类方法返回类实例

时间:2013-05-12 20:33:35

标签: ruby rest neo4j

我试图围绕Neo4j的其余api编写一个包装器。我发现的其他ORM并不能完全按照我的需要去做。我希望有一些模仿ActiveRecord的东西,但是对于一个图形数据库。所以,当我做一些喜欢" NeoRest.find(id = 1)"我希望它返回与该id对应的数据库记录,但我想将其作为NeoRest实例返回。我的代码如下。我已经浏览了整个网络,找不到任何可以帮助我的东西 - 希望这不是一个愚蠢的问题= \

require 'net/http'
require 'uri'
require 'json'

class NeoRest

    def NeoRest.post(key = nil, value = nil)
#       NeoRest.new

        base_url= URI('http://localhost:7474/db/data/node/')

        response = Net::HTTP.post_form(base_url, {key => value})
        decode=JSON.parse(response.body)
        puts decode["self"]
        puts decode["data"]
    end #testrest
end #class

bob=NeoRest.post("name", "josh")
puts bob.class #=> nilclass -- want thiis to be =>NeoRest

2 个答案:

答案 0 :(得分:2)

Ruby方法返回最后一个语句的结果。在您的情况下,puts(...)会返回nil

可能你想要这样的代码:

class NeoRest

    def self.post(key = nil, value = nil)
        new(key, value)
    end

    def initialize(key = nil, value = nil)

        base_url= URI('http://localhost:7474/db/data/node/')

        response = Net::HTTP.post_form(base_url, {key => value})
        @decode=JSON.parse(response.body)
    end
end

答案 1 :(得分:0)

所以我最终得到了我需要的东西。我重新安排了一些东西,但是现在,在.post方法中,我调用了另一个方法,它实例化了NeoRest的一个对象,然后将从REST方法返回的信息传递给它。

class NeoRest
    def self.post(key = nil, value = nil)
        request = Net::HTTP::Post.new("/db/data/node/")
        response = @http.request(request)
        create_instance(response)
    end

    def self.create_instance(response)
        decode=JSON.parse(response.body)
        instance = self.new 
        instance.data=decode["data"]
        puts "created following instance"
        puts instance
        instance
    end
end