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

标签 ruby hanami

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

相关文章:

ruby - Hanami - 如何正确检查模型是否已保留?

ruby - 如何为 Hanami 应用程序配置 Puma?

ruby - gem install bson 在 Windows 10 上失败

arrays - 构造一个内部包含条件逻辑的 Ruby 数组

ruby - 如何使用花见记录器?

ruby - 如何仅更新 Hanami 模型中已更改的属性?

ruby-on-rails - 为什么我使用 Rails 和 grape 得到 "Unable to autoload constant"?

ruby-on-rails - 如何使用 capistrano 处理一次性部署任务?

ruby - 什么是 "terminated object",为什么我不能调用它的方法?

Ruby 1.9.3 Teeny 版本