添加到日期 class 的方法上的 NoMethodError
NoMethodError on method added to Date class
我在Dateclass中添加了两个方法,放在了lib/core_ext
中,如下:
class Date
def self.new_from_hash(hash)
Date.new flatten_date_array hash
end
private
def self.flatten_date_array(hash)
%w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
end
end
然后创建了一个测试
require 'test_helper'
class DateTest < ActiveSupport::TestCase
test 'the truth' do
assert true
end
test 'can create regular Date' do
date = Date.new
assert date.acts_like_date?
end
test 'date from hash acts like date' do
hash = ['1i' => 2015, '2i'=> 'February', '3i' => 14]
date = Date.new_from_hash hash
assert date.acts_like_date?
end
end
现在我收到一个错误:Minitest::UnexpectedError: NoMethodError: undefined method 'flatten_date_array' for Date:Class
是我的方法定义不正确还是怎么的?我什至尝试在 new_from_hash
中移动 flatten_date_array
方法,但仍然出现错误。我也尝试在 MiniTest 中创建测试,但得到了同样的错误。
private 不适用于 class 方法,使用 self。
class Date
def self.new_from_hash(hash)
self.new self.flatten_date_array hash
end
def self.flatten_date_array(hash)
%w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
end
end
我在Dateclass中添加了两个方法,放在了lib/core_ext
中,如下:
class Date
def self.new_from_hash(hash)
Date.new flatten_date_array hash
end
private
def self.flatten_date_array(hash)
%w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
end
end
然后创建了一个测试
require 'test_helper'
class DateTest < ActiveSupport::TestCase
test 'the truth' do
assert true
end
test 'can create regular Date' do
date = Date.new
assert date.acts_like_date?
end
test 'date from hash acts like date' do
hash = ['1i' => 2015, '2i'=> 'February', '3i' => 14]
date = Date.new_from_hash hash
assert date.acts_like_date?
end
end
现在我收到一个错误:Minitest::UnexpectedError: NoMethodError: undefined method 'flatten_date_array' for Date:Class
是我的方法定义不正确还是怎么的?我什至尝试在 new_from_hash
中移动 flatten_date_array
方法,但仍然出现错误。我也尝试在 MiniTest 中创建测试,但得到了同样的错误。
private 不适用于 class 方法,使用 self。
class Date
def self.new_from_hash(hash)
self.new self.flatten_date_array hash
end
def self.flatten_date_array(hash)
%w(1 2 3).map { |e| hash["date(#{e}i)"].to_i }
end
end