B
B
Bogdan2018-06-05 16:26:40
Ruby on Rails
Bogdan, 2018-06-05 16:26:40

Telegram bot, how to properly divide into modules?

Hello. Please tell me how to do it right, I use the telegram-bot gem . And now my main file has grown, and so I decided to throw part of the code into the
/app/controllers/elegram/webhook_controller.rb module

class Telegram::WebhookController < Telegram::Bot::UpdatesController
  include Telegram::Bot::UpdatesController::CallbackQueryContext
  include Telegram::Bot::UpdatesController::MessageContext
  include NotificationsAdditional

  use_session!
  context_to_action!
  before_action :set_locale

  include TelegramAddNotification
 ....

app/controllers/concerns/telegram_add_notification.rb
module TelegramAddNotification
  def new_currency_pair
    markup = setup_button()
    respond_with :message, text: I18n.t(:ask_enter_pair), reply_markup: markup
    save_context :new_currency_pair
  end

  context_handler :new_currency_pair do |*args|
   ...
  end

And when you start the bot, an error immediately flies,
NoMethodError: undefined method `context_handler' for TelegramAddNotification:Module
/coins/app/controllers/concerns/telegram_add_notification.rb:10:in `<module:TelegramAddNotification>'
/coins/app/controllers/concerns/telegram_add_notification.rb:3:in `<main>'
/coins/gems/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:100:in `load'
/coins/gems/gems/bootsnap-1.3.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:100:in `load'

Do not tell me how to properly divide it into modules? Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
printercu, 2018-06-07
@bogdan_uman

In the new version 0.14, `context_handler` has been removed, and there will be no such situations. Despite this, this situation is quite common, and can occur both in a controller with methods `before_action, helper_method`, and in models, for example, with methods `validates, scope, ...`
`context_handler` is a class method, and it is available only in the bot controller, it is not defined for any ruby ​​module. Here we need to correct the code so that `context_handler` is called on the controller when TelegramAddNotification is enabled. Ruby has `Module#included` for this, rails uses the api.rubyonrails.org/classes/ActiveSupport/Concern.html module (I recommend reading the description and source code), which extends the capabilities of `.included`.

module TelegramAddNotification
  extend ActiveSupport::Concern

  included do
    context_handler ...
  end
end

D
dan lar, 2018-06-07
@vortx

Put your piece in the lib folder and check that the lib gets into config.autoload_paths and chain it with require ". /lib/your file".
require 'file' in Lib is also an option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question