我有这段代码,而且效果很好
require "date"
@past = []
@future = []
@artist = Artist.find(2)
def sort_by_date(artist)
artist.events.each do |event|
if event.date < DateTime.now
@past << event.id
else
@future << event.id
end
end
end
def event_title(arr)
arr.each do |event_id|
e = Event.find(event_id)
artist_names = []
e.artists.each do |artist|
unless artist.name == @artist.name
artist_names << artist.name
end
end
puts "#{e.name} with #{artist_names.join(", ")} at #{(Venue.find(e.venue_id)).name}"
end
end
sort_by_date(@artist)
puts "Upcoming Events: "
event_title(@future)
puts "Past Events: "
event_title(@past)
我想将此操作包装到模块中,但我无法理解如何正确地将artist_id
传递给它。使用此命令rails runner app/modules/artist_event_sort.rb
,我收到此错误:``&#39 ;: undefined method sort_by_date' for SortedArtistEvents:Module (NoMethodError)
。在我尝试将整个操作包装到一个模块之前,sort_by_date
和event_title
这两种方法正常运行,因此我知道我错过了什么。
module SortedArtistEvents
require "date"
attr_accessor :artist_id
def initialize(artist_id)
@past = []
@future = []
@artist = Artist.find(artist_id)
end
def sort_by_date(artist)
artist.events.each do |event|
if event.date < DateTime.now
@past << event.id
else
@future << event.id
end
end
end
def event_title(arr)
arr.each do |event_id|
e = Event.find(event_id)
artist_names = []
e.artists.each do |artist|
unless artist.name == @artist.name
artist_names << artist.name
end
end
puts "#{e.name} with #{artist_names.join(", ")} at #{(Venue.find(e.venue_id)).name}"
end
end
sort_by_date(@artist)
puts "Upcoming Events: "
self.event_title(@future)
puts "Past Events: "
event_title(@past)
end
class LetsSort
include SortedArtistEvents
end
test_artist_sort = LetsSort.new(2)
答案 0 :(得分:0)
看起来这里有一些错误。您正在尝试初始化模块,您只能初始化一个类,例如class SortedArtistEvents
。
如果你有这个:
module Foo
def bar; end
end
bar
只能通过包含或扩展Foo
的模块或类来访问。如果出现错误undefined method sort_by_date' for SortedArtistEvents:Module
,则必须执行
module SortedArtistsEvents
def self.sort_by_date; end
end
获取SortedArtistsEvents.sort_by_date