Brandon
Brandon

Reputation: 1465

Ruby on rails Access a file from a controller

If I am going about this wrong please let me know I can change it. I have a file in config/initializers/payload_signer.rb. I am trying to use this file in the controller that is called device_enrollment_controller.rb.

PayloadSigner.sign(get_profile)

get_profile is a method in the controller that gets the file I need and returns it. PayloadSigner references the other file. When I try to run this (keeping in mind im sure changes will have to be made in payload_signer for it work right) the error I get is uninitialized constant DeviceEnrollmentController::PayloadSigner. This leads me to believe I am referencing the payload_signer.rb file incorrectly. I have tried things like include and load but so far they are not working.

Any help or guidance is appreciated.

Upvotes: 0

Views: 212

Answers (1)

lipanski
lipanski

Reputation: 1763

Rails Initializers are called before Controllers or Models. So it won't work. Initializers are not intended for this kind of use. Instead I suggest placing your code in a controller before_filter. Either in the ApplicationController or only in those controllers that require it (e.g. DeviceEnrollmentController). Something like this:

class DeviceEnrollmentController # Or ApplicationController

  before_filter :sign_payload

  protected

  def get_profile
    # Magic
  end

  def sign_payload
    PayloadSigner.sign(get_profile)
  end
end

EDIT: Another example:

class DeviceEnrollmentController

  # The filter is only applied to the sign action
  # (that's what the :only parameter does).
  before_filter :sign_payload, :only => [:sign]

  # Browsing to /show, you render this magic button of yours.
  def show
    # Render page that holds the button
  end

  # The magic button is bound to the /sign route.
  # Clicking on the button calls this action.
  def sign
    # When you get here, the #sign_payload method
    # has already been called.
  end

  protected

  def get_profile
    # Magic
  end

  def sign_payload
    PayloadSigner.sign(get_profile)
  end
end

Upvotes: 1

Related Questions