Home > Net >  Standalone class generating method_missing
Standalone class generating method_missing

Time:11-03

In a Rails application an ad hoc class is defined

class TwitterClient

  BASE_URL = 'https://api.twitter.com/2/'

  def initialize(twitter_account)
    @twitter_account = twitter_account
Rails.logger.info @twitter_account.inspect
  end

  def me
    path = BASE_URL.to_s   'users/me'
    get path
  end

  private

    def get(path)
      request(:get, path)
    end
end

Verifying via the console, an object can be created

 c = TwitterAccount.first
=>
#<TwitterAccount:0x00000001086c5c10

however, calling the me method on that object c.me returns an error:

.rbenv/versions/3.1.2/lib/ruby/gems/3.1.0/gems/activemodel-7.0.4/lib/active_model/  
attribute_methods.rb:458:in `method_missing': undefined method `me' for #<TwitterAccount

Where is this mistaken?

CodePudding user response:

I may as well stick it as an answer to help other devs stuck out there,

c does not seem to be an instance of TwitterClient but of TwitterAccount. If you want to have access to a method in the TwitterClient class you need to create an instance of it:

twitter_client = TwitterClient.new(twitter_account)

then you can access the me method like:

twitter_client.me

  • Related