我正在使用 Hanami,并在 /lib/supports/utils.rb 中创建了一个自定义模块。我要求位于 /lib/myapp 中的 /lib/supports 的所有文件如下所示:
require 'hanami/model'
require 'hanami/mailer'
Dir["#{__dir__}/myapp/**/*.rb"].each { |file| require_relative file }
Dir["#{__dir__}/supports/**/*.rb"].each { |file| require_relative file }
Hanami::Model.configure do
# and so on
在/lib/supports/utils.rb中,我有:
# using the gem 'slugify'
require 'slugify'
module MyModule
module Utils
module Slug
def slug_it(random = false)
if random
slugify + '-' + SecureRandom.hex(10).to_s
else
slugify
end
end
end
end
end
我尝试将 MyModule::Utils::Slug 包含在存储库中,但它总是返回 NoMethodError: undefined method `slug_it' for "string":String。一个例子:
class EventRepository
include Hanami::Repository
include MyModule::Utils::Slug
def self.create_or_update(attrs)
found = find(attrs.id)
attrs = event_attributes(attrs)
if found
unless found.slug.include? attrs[:name].slug_it
attrs[:slug] = attrs[:name].slug_it(true)
end
found.update(attrs)
update found
else
attrs[:slug] = attrs[:name].slug_it(true)
create Event.new(attrs)
end
end
end
只有在 /lib/supports/utils.rb 底部添加时才有效:
class String
include MyModule::Utils::Slug
end
我希望始终在 EventRepository 中包含 include Hanami::Repository
等模块。
我做错了什么?
最佳答案
当您将 MyModule::Utils::Slug
包含到 EventRepository
中时,包含的模块中定义的方法可在 EventRepository
的实例上使用> 不在 String
上。如果您想按原样使用该模块,则需要将其包含在 String
中。如果您不想将其包含在全局类中,您可以这样做
module MyModule
module Utils
module Slug
def slug_it(string, random = false)
if random
string.slugify + '-' + SecureRandom.hex(10).to_s
else
string.slugify
end
end
end
end
end
然后修改 slug 创建以传递您想要的字符串slugify
unless found.slug.include? slug_it(attrs[:name])
attrs[:slug] = slug_it(attrs[:name], true)
end
关于ruby - 无方法错误 : undefined method for String with custom module in Hanami,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37551412/