Richlewis Richlewis - 1 month ago 8
Ruby Question

Undefined method for class - Sinatra

It seems i don't quite understand initializing or using a class within another class.

I have a Sinatra app and have created a class to handle fetching data from an api

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


I then have another class that needs to consume/use the
check_frame_number
method

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


When
check_frame_number
is called i get a
undefined method
error. What i would like to know is what basic thing am i not doing/understanding, I thought by requiring the file which has the class it would be available to use.

Any help appreciated

Thanks

Answer

No, you can not require a method defined in class - methods defined in class only available to class, class instances and within the inheritance.

Mixing method only possible with including modules.

To solve you issue you could either do

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

or write a module with the method and include/extend in class, you want that method to be available in.

Comments