Search code examples
ruby-on-railsservicecontrollernameerror

RoR: NameError: Uninitialized constant (Service)


This is my first question at I'm quite new to RoR and I try to understand the PINGOWebApp, which you can find here https://github.com/PingoUPB/PINGOWebApp. They specified their "question" model (app/models/question.rb) in different types of questions in app/services/ (e.g. number_question.rb, text_question.rb), all inheriting from app/services/generic_question.rb:

class GenericQuestion < Delegator
  
  def initialize(question)
    super
    @question = question
  end
  
  def __getobj__ # required
    @question
  end
  
  def __setobj__(obj)
      @question = obj # change delegation object
  end
  
  def to_model
    @question.to_model
  end

  def has_settings?
    false
  end

  def add_setting(key, value)
    @question.settings ||= {}
    @question.settings[key.to_s] = value.to_s
  end
  
  def self.model_name
    Question.model_name
  end
  
  def self.reflect_on_association arg
    Question.reflect_on_association arg
  end
  
  alias_method :question, :__getobj__ # reader for survey
  
end

Here comes my first questions:

  1. Since there's no service generator, they must have created all the ruby-files in app/service/ by hand, haven't they? Or what other ways are there?

  2. I forked the project and added another service by hand, called dragdrop_question.rb, and integrated it into the question_controller.rb:

class QuestionsController < ApplicationController
  def new
    @question_single = SingleChoiceQuestion.new.tap { |q| q.question_options.build }
    @question_multi = MultipleChoiceQuestion.new.tap { |q| q.question_options.build }
    @question_text = TextQuestion.new
    @question_number = NumberQuestion.new  #refactor this maybe?
    @question_dragdrop = DragDropQuestion.new.tap { |q| q.answer_pairs.build }
  end
end

I also adapted the view and tested it locally. I got NameError at /questions/new uninitialized constant QuestionsController::DragDropQuestion.
If I add

require_dependency "app/services/dragdrop_question.rb"

to the question_controller.rb the error is gone, but they haven't done it anything like that. So how do they introduce the services to controllers?

Thanks for any help in advance, especially for tutorials or book references what explain the controller-model-view-service schema.


Solution

  • Try to follow the right naming convention, your class name is DragDropQuestion therefore the expected file name is drag_drop_question.rb.