1

I'm building a web API with Ruby and Grape. I have two classes that requires each other which leads to a situation where I get uninitialized constant class errors. The place where I get the error is in the Entity class for Connector, see the example code below, which requires Card::Entity before it has been inintialized. Is there any way to solve this probelm without moving the Entity definitions to another file?

#card.rb
require_relative 'connector'
require_relative 'caption'

class Card < ActiveRecord::Base

  belongs_to  :medium
  belongs_to  :storyline

  has_many    :connectors, autosave: true
  has_many    :connected_cards, class_name: "Connector", foreign_key: "connected_card_id"
  has_many    :captions

  accepts_nested_attributes_for :connectors, :captions

  class Entity < Grape::Entity
    expose :id, documentation: { readonly: true }
    expose :cardtype
    expose :connectors, using: Connector::Entity
    expose :captions, using: Caption::Entity
  end
end

#connector.rb
require_relative 'card'

class Connector < ActiveRecord::Base
  has_one  :card
  has_one  :connected_card, :class_name => "Card", :foreign_key => "connected_card_id"

  class Entity < Grape::Entity
    expose :id, documentation: { readonly: true }
    expose :title
    expose :card, using: Card::Entity
    expose :connected_card, using: Card::Entity
  end
end
Abris
  • 1,451
  • 3
  • 18
  • 38
  • 1
    ...I feel like you should redesign this bit of your program, because this seems like a symptom of something worse – Nic May 02 '15 at 14:35

1 Answers1

2

I don't know a lot about grape, but this could be solved by "pre declaring" the class:

#card.rb
require_relative 'caption'

class Connector < ActiveRecord::Base
  # empty declaration just to make the import works
end

class Card < ActiveRecord::Base
  belongs_to  :medium
  belongs_to  :storyline

  has_many    :connectors, autosave: true
  has_many    :connected_cards, class_name: "Connector", foreign_key: "connected_card_id"
  has_many    :captions

  accepts_nested_attributes_for :connectors, :captions
  ...
end

Still, I think that QPaysTaxes may have a valid point about design here.

Martin
  • 7,634
  • 1
  • 20
  • 23
  • Ok, yeah this worked but it is not a solution I want to go forward with. I did as QPaysTaxes suggested and redesigned it instead. – Abris May 03 '15 at 08:44
  • Looks good to me - agree that this was answering the "how can I make this work" more than a valid solution. – Martin May 03 '15 at 09:33