Rober
Rober

Reputation: 6108

Service objects pattern in Ruby on Rails

I´m trying to develop a service class that provides payment services in my Rails app, but it´s not working.

Service class (lib/paypal_service.rb) (not sure if it should be placed here, I read it in some posts):

class PaypalService
  attr_reader :api #, :express_checkout_response  

  def initialize()
    @api = PayPal::SDK::Merchant::API.new    
  end

  def test()
    puts "Congratulations, you have called test"
  end
end

Controller (uses service):

class BookingsController < ApplicationController
  include BoatsHelper
  require 'paypal_service'

  def create
    PaypalService.test   
  end 

...

In output I get:

 NoMethodError (private method `test' called for PaypalService:Class):

Upvotes: 1

Views: 1221

Answers (2)

Kirti Thorat
Kirti Thorat

Reputation: 53018

Use PaypalService.new.test instead of PaypalService.test as test is an instance method of class PaypalService and not a class method. Update it as below:

class BookingsController < ApplicationController
  include BoatsHelper
  require 'paypal_service'

  def create
    PaypalService.new.test   
  end 

...

NOTE:

If you want to call it as PaypalService.test then you can convert test to a class method as follows:

class PaypalService
  attr_reader :api #, :express_checkout_response  

  def initialize
    @api = PayPal::SDK::Merchant::API.new    
  end

  def self.test
    puts "Congratulations, you have called test"
  end
end

Upvotes: 1

jordelver
jordelver

Reputation: 8432

It's because you are calling a class method, but you have defined an instance method.

Change you controller to this

def create
  PaypalService.new.test   
end

Or define a class method and leave your controller as is

class PaypalService
  attr_reader :api #, :express_checkout_response  

  def initialize()
    @api = PayPal::SDK::Merchant::API.new    
  end

  def self.test
    new.test
  end

  def test()
    puts "Congratulations, you have called test"
  end
end

Upvotes: 3

Related Questions