我们有2个模型:估价和文件.两者都在微服务中,因此我们使用ActiveResource来访问它们.
class Valuation < ActiveResource::Base
self.site = "#{config.valuation_service.base_url}/valuations"
self.include_root_in_json = false
end
class Document < ActiveResource::Base
self.site = "#{config.valuation_service.base_url}/documents"
self.include_root_in_json = true
end
Run Code Online (Sandbox Code Playgroud)
在开发中运行Rails控制台.
>> Valuation.new(documents: [{ title: 'Foo' }])
=> <Valuation:0x007f9af85f1708 @attributes={"documents"=>[#<Valuation::Document:0x007f9af85f0970 @attributes={"title"=>"Foo"}, @prefix_options={}, @persisted=false>]}, @prefix_options={}, @persisted=false>
Run Code Online (Sandbox Code Playgroud)
所以文档的类名是Valuation:Document.在生产中运行rails控制台时
>> Valuation.new(documents: [{ title: 'Foo' }])
=> <Valuation:0x007f9af595b478 @attributes={"documents"=>[#<Document:0x007f9af595a500 @attributes={"title"=>"Foo"}, @prefix_options={}, @persisted=false>]}, @prefix_options={}, @persisted=false>
Run Code Online (Sandbox Code Playgroud)
文档的类只是Document和它一样尊重配置include_root_in_json.
更大的问题是在调用.to_json对象时.
# development
>> Valuation.new(documents: [{ title: 'Foo' }]).to_json
=> "{\"documents\":[{\"title\":\"Foo\"}]}"
# production
>> Valuation.new(documents: [{ title: 'Foo' …Run Code Online (Sandbox Code Playgroud) 在irb控制台中我创建了一个类'Hello'
irb(main):001:0> class Hello
irb(main):002:1> end
=> nil
Run Code Online (Sandbox Code Playgroud)
并在'Hello'类之外创建了一个名为'hi'的方法
irb(main):003:0> def hi
irb(main):004:1> 'hiiii'
irb(main):005:1> end
=> :hi
Run Code Online (Sandbox Code Playgroud)
现在这个hi方法充当类方法和实例方法
irb(main):006:0> Hello.hi
=> "hiiii"
irb(main):007:0> Hello.new.hi
=> "hiiii"
irb(main):008:0> hi
=> "hiiii"
Run Code Online (Sandbox Code Playgroud)
为什么这个hi方法是使用类'Hello'调用,即使它在'Hello'类上下文之外?
我有一个问题:是否有任何相反的方法,.include?我知道有unless,但我想要做到这一点的if,可以吗?我尝试过unless:
unless variable.include?("something")
#..
end
Run Code Online (Sandbox Code Playgroud)
我想这样做if,可以吗?我知道,.!include?但它不起作用(我真的不知道这种方法是否存在,但我在这个论坛中看到了它).