我正在使用Hanami,我在 /lib/supports/utils.rb 中创建了一个自定义模块。我要求 / lib / myapp 中所有位于 / lib / supports 的文件,如下所示:
curl_easy_setopt(m_curlHandle, CURLOPT_CAINFO, *<value> )
在 /lib/supports/utils.rb 中,我有:
CURLOPT_CAINFO
我尝试在存储库中包含 MyModule :: Utils :: Slug ,但它总是返回 NoMethodError:未定义的方法`slug_it'代表“string”:String 。一个例子:
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
我希望始终在EventRepository中包含 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
等模块。
我做错了什么?
答案 0 :(得分:3)
当您将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
答案 1 :(得分: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
答案 2 :(得分:0)
另一种方法是:
[{
"rating": 3.0,
"ratingsPK": {
"movieId": 2017,
"userId": 610
},
"timestamp": 913815387
}, {
"rating": 5.0,
"ratingsPK": {
"movieId": 2017,
"userId": 654
},
"timestamp": 959098930
}, {
"rating": 4.0,
"ratingsPK": {
"movieId": 2017,
"userId": 856
},
"timestamp": 1059863336
}, {
"rating": 2.0,
"ratingsPK": {
"movieId": 2017,
"userId": 903
},
"timestamp": 903628492
}, {
"rating": 3.5,
"ratingsPK": {
"movieId": 2017,
"userId": 1185
},
"timestamp": 1100560205
}]
然后你可以像这样使用它:
require 'slugify'
module MyModule
module Utils
module Slug
def self.slug_it(string, random = false) # Please note `self` and `string`
# ...
end
end
end
end