类的未定义方法 - Sinatra

时间:2016-11-02 09:40:37

标签: ruby sinatra

我似乎不太了解在另一个类中初始化或使用类。

我有一个Sinatra应用程序并创建了一个类来处理从api

获取数据
# path: ./lib/api/bikes/bike_check
class BikeCheck
  def self.check_frame_number(argument)
    # logic here
  end
end
BikeCheck.new

然后我有另一个需要使用/ check_frame_number方法的类

require 'slack-ruby-bot'
# Class that calls BikeCheck api
require './lib/api/bikes/bike_check'

class BikeCommands < SlackRubyBot::Bot
  match /^Is this bike stolen (?<frame_number>\w*)\?$/ do |client, data, match|
    check_frame_number(match[:frame_number])
    client.say(channel: data.channel, text: @message)
  end
end
BikeCommands.run

调用check_frame_number时出现undefined method错误。我想知道的是我没有做什么/理解什么基本的东西,我想通过要求具有可以使用的类的文件。

1 个答案:

答案 0 :(得分:1)

不,你不能要求在类中定义的方法 - 在类中定义的方法只能用于类,类实例和继承。

混合方法仅适用于包含模块。

要解决您的问题,您可以这样做

    function shortener(s, n){
    
        var ret = "";
        if(s.charAt(n) !== " "){
            var fullWords = s.substring(0, n).split(" ").length - 1;
            ret = s.split(" ").splice(0, fullWords).join(" ");
        }
        else{
            ret = s.substring(0, n);
        }
        return ret + " ...";
    }
    var s = "It's important to remember that this function does NOT replace newlines  with <br> tags. Rather, it inserts a <br> tag before each newline, but  it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved. ";

    console.log(shortener(s, 16));
    console.log(shortener(s, 4));
    console.log(shortener(s, 80));

或者在课程中使用方法和class BikeCommands < SlackRubyBot::Bot match /^Is this bike stolen (?<frame_number>\w*)\?$/ do |client, data, match| BikeCheck.check_frame_number(match[:frame_number]) # <=========== client.say(channel: data.channel, text: @message) end end / include编写模块,您希望该方法可用。