marcelo
marcelo

Reputation: 193

Ruby returns TypeError: can't convert Object into String

I'm starting to work with Ruby and I have the following module:

module RadioreportHelper
  @totalsum = 0
  @radio
  @daysAndTotals

  def load(service, transactionsPerDay)
    puts "#{service} : #{transactionsPerDay}"
    @radio = service
    @daysAndTotals = transactionsPerDay

    transactionsPerDay.each{|day, total|
      @totalsum += total
    }
  end
  attr_reader :radio, :daysAndTotals, :totalsum
end

I'm running the following unit test case:

class RadioreportHelperTest < ActionView::TestCase
  fixtures :services
  def test_should_return_populated_radio_module
    service = Service.find_by_name("Mix")
    transactionsPerDay = {1=>20, 2=>30, 4=>40, 5=>50}
    radioReport = RadioreportHelper.load(service, transactionsPerDay)
    assert_not_nil(radioReport)
    assert_equal("Mix", radioReport.radio.name)
  end
end

But I always get the following error: TypeError: can't convert Service into String

I want the service object to be in the module RadioreportHelper and stored it in the @radio variable not the string. Thanks, for the all the help guys!

Upvotes: 0

Views: 5244

Answers (2)

zetetic
zetetic

Reputation: 47548

Try adding a to_s method to your Service model.

def to_s
  service # or some other method in the model that returns a string
end

It is not necessary to call to_s from inside an interpolated expression, i.e. "#{service}" will return the result of service.to_s.

EDIT

Never mind all of this. Your RadioreportHelper.load method is not being reached -- instead you are getting load from ActiveSupport::Dependencies::Loadable. Try renaming the load method to something else.

(I hate name collisions.)

Upvotes: 1

Brett Bender
Brett Bender

Reputation: 19738

You should definitely try this:

puts "#{service.to_s} : #{transactionsPerDay}"

Although I am not sure how interpolation for hashes is handled in strings either, so you may need to use

puts "#{service.to_s} : #{transactionsPerDay.to_s}"

Upvotes: 1

Related Questions