2

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

我想总是像include Hanami::RepositoryEventRepository 一样包含模块。

我究竟做错了什么?

4

3 回答 3

3

当您包含MyModule::Utils::Slug到时,包含模块中定义的方法在not onEventRepository的实例上可用。如果要按原样使用模块,则需要将其包含在. 如果您不想将其包含在全局课程中,您可以这样做EventRepositoryStringString

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
于 2016-05-31T17:41:43.997 回答
0

你也可以试试类似的东西:

https://gist.github.com/rafaels88/5529b3863c699b1cd4d20265c32d4a21

# lib/your_app/ext/sluggable.rb

module Sluggable
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def sluggable(field)
      @field = field
    end

    def field
      @field
    end
  end

  def slug
    send(self.class.field).slugify
  end
end

# USAGE
#
# class MyEntity
#  include Hanami::Entity
#  include Sluggable

#  attributes :name, :slug, :other_field, :yet_another_field
#  sluggable :name
# end
#
# Do not forget to create :slug field in database and mapping it to its entity
于 2016-09-14T18:37:21.530 回答
0

另一种方法是:

require 'slugify'

module MyModule
  module Utils
    module Slug
      def self.slug_it(string, random = false) # Please note `self` and `string`
        # ...
      end
    end
  end
end

然后你可以像这样使用它:

MyModule::Utils::Slug.slug_it(attrs[:name], true)
于 2017-01-09T08:04:28.030 回答