gpt4 book ai didi

ruby - 无方法错误 : undefined method for String with custom module in Hanami

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:59 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com