Tag: 包括

在使用Ruby on Rails ActiveSupport :: Concernfunction时如何“嵌​​套”模块的包含?

我正在使用Ruby 1.9.2和Ruby on Rails v3.2.2 gem。 我希望“嵌套”包含模块,因为我使用的是RoR ActiveSupport :: Concernfunction,但我怀疑应该在哪里说明include方法。 也就是说,我有以下几点: module MyModuleA extend ActiveSupport::Concern # include MyModuleB included do # include MyModuleB end end 我应该在include MyModuleB的“body”/“context”/“scope”中声明包含MyModuleA还是应该在included do … end块中声明? 有什么区别,我应该从中得到什么?

从Ruby中包含的文件中访问变量

如何访问包含文件中定义的变量? # inc.rb foo = “bar”; # main.rb require ‘inc.rb’ puts foo # NameError: undefined local variable or method `foo’ for main:Object

Ruby mixins:扩展和包含

我一直在阅读一些关于Ruby的mixin方法, extend和include ,我仍然不太确定这种行为。 我理解, extend会将给定模块的实例方法作为单例方法添加到执行扩展的模块中,并且include将基本上将模块的内容(方法,常量,变量)附加到执行包含的模块中,有效地定义他们在接收器中。 然而,经过一些修补,试图了解行为将如何表现,我有几个问题。 这是我的测试设置: module Baz def blorg puts ‘blorg’ end end module Bar include Baz def blah puts ‘blah’ end end module Foo extend Bar end class Bacon extend Bar end class Egg include Bar end 正如我所料,模块Bar获得了Baz ( #blorg )中定义的实例方法,好像它们由于包含方法而自己定义,而类Bacon获得了单例方法Bacon::blah和Bacon::blorg通过扩展。 Bacon.blah # => blah Bacon.blorg # => blorg 而类Egg获得Bar ( #blah和现在#blorg […]

如何在我的.rb文件中共享变量?

我有几个.rb文件,我想在所有这些文件中使用相同的变量。 假设我的所有.rb文件都可以访问变量test_variable = “test” 。 我怎样才能做到这一点? 我使用test_variable = “test”创建了settings.rb文件,然后在另一个.rb文件中使用了test_variable = “test” require ‘settings’ ,但它没有用。 我想使用require not load 。 我试图通过在变量名前加上$来使变量成为全局变量,但我仍然在undefined local variable or method ‘test_variable’ for main:Object (NameError)获取undefined local variable or method ‘test_variable’ for main:Object (NameError) 。