我有我想要包括類和實例方法的Ruby類。繼模式描述here,我目前使用下列內容: class SomeObject
include SomeObject::Ability
def self.some_builder_method(params)
# use some_class_method ...
end
end
module SomeObje
讓我們打開類Module,並添加一個方法吧: class Module
def foo
puts "phew"
end
end
我可以這樣調用這個方法, Class.foo
這是可以理解因爲Class的等級是Class,其超類是Module。因此它可以調用在Module中定義的實例方法。現在 ,下面的方法bar定義上Module的eigenclass: cl
我試圖在我的Product model中測試方法cumulative_cost。 #app/models/product.rb
class Product < ActiveRecord::Base
class << self
def cumulative_cost
self.sum(:cost)
end
end
end
所以我會運行類似P
我創建了一個包含常量NAME和方法hello的模塊。如果一個類包含模塊,那麼這兩個定義應該在不同的範圍內可見。 module A
NAME = 'Otto'
def self.included(base)
base.extend(ClassMethods)
end
def hello(name = 'world')
self.class
我有一個爲子類化構建的類。 class A
def initialize(name)
end
def some
# to define in subclass
end
end
# usage
p A.new('foo').some
#=> nil
在我的用例中,我不想創建一個子類,因爲我只需要一個實例。因此,我會更改initiali
我在代碼片段中使用了以下語法,我不確定它的功能。 class << PushableModule = Module::new
def new *args, &blk
m = Module::new(*args, &blk)
m.extend Pushable
m
end
end
首先,類或模塊PushableModule不會在文件/程序存在,其次這似乎是發生
這部分作品: class Example1
@@var1= "var1 in the Example1"
def get_var1
@@var1
end
end
example1 = Example1.new
example1.get_var1
# => "var1 in the Example1"
但如果我嘗試eigenclass: def